package com.chenyang.nse.bussiness.bean;

import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.odbc.DbCache;
import com.chenyang.nse.bussiness.service.core.impl.DataSystemServiceImpl;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@EnableScheduling
public class DataCache {
   @Autowired
   TCoreDatasystemDao datasystemDao;
   @Autowired
   DataSystemServiceImpl dataSystemService;
   private ExecutorService executorService = Executors.newFixedThreadPool(20);
   public static List<DataBase> dataList = new CopyOnWriteArrayList();

   @Scheduled(
      cron = "0 0/20 * * * ?"
   )
   public void cacheData() throws InterruptedException {
      List<TCoreDatasystem> dataSystemList = this.datasystemDao.queryAll();

      for(int i = dataList.size() - 1; i >= 0; --i) {
         DataBase dataBase = (DataBase)dataList.get(i);
         boolean find = false;

         for(TCoreDatasystem datasystem : dataSystemList) {
            if (datasystem.getId().equals(dataBase.getDatasystemid())) {
               find = true;
               break;
            }
         }

         if (!find) {
            dataList.remove(dataBase);
         }
      }

      CountDownLatch cdl = new CountDownLatch(dataSystemList.size());

      for(TCoreDatasystem datasystem : dataSystemList) {
         Runnable cacheThread = null;
         Object var11;
         if ("HIVE_TDH".equals(datasystem.getDbtype())) {
            var11 = new CacheHiveTDH(this.dataSystemService, datasystem, cdl);
         } else if ("MONGODB".equals(datasystem.getDbtype())) {
            var11 = new CacheMongodb(this.dataSystemService, datasystem, cdl);
         } else if ("ES".equals(datasystem.getDbtype())) {
            var11 = new CacheElasticSearchThread(this.dataSystemService, datasystem, cdl);
         } else {
            var11 = new CacheThread(this.dataSystemService, datasystem, cdl);
         }

         this.executorService.execute((Runnable)var11);
      }

      cdl.await();
      DbCache.sync();
   }
}
