package com.bonus.mq.rabbit.tx;

import com.bonus.mq.MQProperties;
import com.bonus.mq.MQTemplate;
import com.bonus.mq.tx.DefaultTxMessageManager;
import com.bonus.mq.tx.MQTxCheckComposite;
import com.bonus.mq.tx.TxMessageManager;
import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.handler.IJobHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class MessageManagerConfiguration {
   @Configuration
   @ConditionalOnMissingBean({TxMessageManager.class})
   static class DataSourceMessageManagerConfiguration {
//      @Configuration
//      @ConditionalOnMissingBean({DataSource.class})
//      static class DefaultMessageManagerConfigure {
//         @Bean
//         public TxMessageManager messageManager() {
//            return new DefaultTxMessageManager();
//         }
//      }

      @Configuration
//      @ConditionalOnBean({DataSource.class})
      static class DataSourceMessageManagerConfigure {
         @Configuration
//         @ConditionalOnMissingClass({"net.xnzn.framework.data.dataset.datasource.RoutingDataSource"})
         static class DefaultDataSourceMessageManagerConfigure {
            @Bean
            public TxMessageManager messageManager(DataSource dataSource) {
               return new DataSourceTxMessageManager(dataSource);
            }
         }

//         @Configuration
//         @ConditionalOnClass({RoutingDataSource.class})
//         static class DefaultRoutingDataSourceMessageManagerConfigure {
//            @Bean
//            public TxMessageManager messageManager(RoutingDataSource routingDataSource) {
//               return new DataSourceTxMessageManager(routingDataSource.getSystemDataSource().getMasterDataSource());
//            }
//         }
      }
   }

   @Configuration
   @ConditionalOnClass({IJobHandler.class})
   @ConditionalOnMissingBean({TxCheckJobHandler.class})
   static class JobConfigure {
      @Bean
      public IJobHandler txCheckJobHandler(MQProperties mqProperties, TxMessageManager txMessageManager, MQTxCheckComposite mqTxCheckComposite, MQTemplate mqTemplate) {
         IJobHandler jobHandler = new TxCheckJobHandler(txMessageManager, mqTxCheckComposite, mqTemplate);
         XxlJobExecutor.registJobHandler(mqProperties.getRabbitmq().getTxCheckTaskName(), jobHandler);
         return jobHandler;
      }
   }
}
