package com.tsi.sig.server.scheduler;

import com.tsi.sig.server.app.AppUtils;
import com.tsi.sig.server.mapper.MainMapper;
import com.tsi.sig.server.repository.ApplicationRepository;
import com.tsi.sig.server.vo.CvibNodeVO;
import com.tsi.sig.server.websocket.AllTopicCvimHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.KafkaException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;

@Slf4j
@EnableScheduling
@Component
public class TsiSigScheduler {

    public TsiSigScheduler() {
    }

    @PreDestroy
    public void onShutDown() {
    }

    @Async
    @Scheduled(cron = "0 * * * * *")  // 1분 주기 작업 실행
    public void jobLoadDatabase() throws Exception, KafkaException {
        AllTopicCvimHandler allTopicCvimHandler = (AllTopicCvimHandler) AppUtils.getBean(AllTopicCvimHandler.class);
//        OneTopicCvimHandler oneTopicCvimHandler = (OneTopicCvimHandler) AppUtils.getBean(OneTopicCvimHandler.class);
//        try {
            allTopicCvimHandler.start();
//            oneTopicCvimHandler.start();
//        }
//        catch (Exception e) {
//            log.error("NullPointerException AllTopicCvimHandler Start Failed...");
//        }
//        catch(IllegalThreadStateException ie) {
//            log.error("IllegalThreadStateException AllTopicCvimHandler Start Failed...");
//        }
    }

    @Async
    @Scheduled(cron = "0 30 * * * ?")  // 30분 주기 작업 실행
    public void jobLoadLinkList() {
        MainMapper mapper = (MainMapper)AppUtils.getBean(MainMapper.class);
//        try {
            ApplicationRepository repo = (ApplicationRepository) AppUtils.getBean(ApplicationRepository.class);
            List<CvibNodeVO> list = mapper.getNodeList();
            repo.getNodeList().clear();
            for (CvibNodeVO vo : list) {
                repo.getNodeList().add(vo);
            }
//        } catch (Exception e) {
//            log.error("jobLoadLinkList Scheduled Failed...");
//        }
    }

}
