package com.tsi.comm.server;

import com.tsi.app.common.app.AppUtils;
import com.tsi.comm.server.config.TsiCvimServerConfig;
import com.tsi.comm.server.kafka.KafkaConsumerService;
import com.tsi.comm.server.kafka.KafkaProducerService;
import com.tsi.comm.server.mybatis.TsiDatabaseService;
import com.tsi.comm.server.mybatis.vo.AbstractDbmsVo;
import com.tsi.comm.server.mybatis.vo.AlarmOccrVo;
import com.tsi.comm.server.process.dbms.TsiCvimDbmsProcess;
import com.tsi.comm.server.process.logging.TsiCvimLoggingProcess;
import com.tsi.comm.server.process.packet.TsiCvimPacketProcess;
import com.tsi.comm.server.repository.ApplicationRepository;
import com.tsi.comm.server.repository.TsiSessionManager;
import com.tsi.comm.server.tcp.TsiCvimServer;
import com.tsi.comm.server.vo.TsiAlarmConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@SpringBootApplication
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.tsi.app.common", "com.tsi.comm.server.config", "com.tsi.comm.server"})
public class TsiCommServerApplication implements CommandLineRunner, ApplicationListener<ContextClosedEvent>, InitializingBean, DisposableBean {

    public static final String APPLICATION_NAME = "tsi-comm-server";

    private String applicationName = APPLICATION_NAME;

    public static void main(String[] args) {
        SpringApplication application = new SpringApplicationBuilder()
                .sources(TsiCommServerApplication.class)
                .listeners(new ApplicationPidFileWriter("./conf/" + APPLICATION_NAME + ".pid"))
                .initializers(new AppNameInitializer())
                .build();
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("");
        log.info("");
        log.info("************************************************************************************");
        log.info("**                                                                                **");
        log.info("**                               TSI CVIM System                                  **");
        log.info("**                      CVIM Communication Server Program.                        **");
        log.info("**                                                                                **");
        log.info("**                                                                   [ver.1.0]    **");
        log.info("** startup: {}", sdfDate.format(new Date()));
        log.info("************************************************************************************");

        TsiCvimServerConfig config = (TsiCvimServerConfig) AppUtils.getBean(TsiCvimServerConfig.class);

        applicationName = APPLICATION_NAME + "-" + config.getServerId();
        ApplicationRepository.processStateVo.setProcessId(applicationName);
//        TsiAlarmManager alarmManager = (TsiAlarmManager) AppUtils.getBean(TsiAlarmManager.class);
//        alarmManager.getProcessStateVo().setProcessId(APPLICATION_NAME + "-" + config.getServerId());

        TsiDatabaseService tsiDatabaseService = (TsiDatabaseService) AppUtils.getBean(TsiDatabaseService.class);
        tsiDatabaseService.init();

        TsiCvimLoggingProcess loggingProcess = (TsiCvimLoggingProcess) AppUtils.getBean(TsiCvimLoggingProcess.class);
        loggingProcess.start();

        TsiCvimDbmsProcess dbmsProcess = (TsiCvimDbmsProcess) AppUtils.getBean(TsiCvimDbmsProcess.class);
        dbmsProcess.start();

        TsiCvimPacketProcess packetProcess = (TsiCvimPacketProcess) AppUtils.getBean(TsiCvimPacketProcess.class);
        packetProcess.start();

        TsiSessionManager sessionManager = (TsiSessionManager) AppUtils.getBean(TsiSessionManager.class);
        sessionManager.start();

        TsiCvimServer cvimServer = (TsiCvimServer)AppUtils.getBean(TsiCvimServer.class);
        cvimServer.run();

        KafkaConsumerService kafkaConsumerService = (KafkaConsumerService) AppUtils.getBean(KafkaConsumerService.class);
        kafkaConsumerService.start();

        KafkaProducerService kafkaProducerService = (KafkaProducerService) AppUtils.getBean(KafkaProducerService.class);
        kafkaProducerService.start();

        config.setStartup(true);
        try {
            // 시스템 시작 알람 이력 저장
            AlarmOccrVo alarm = new AlarmOccrVo(AbstractDbmsVo.DBMS_ALARM_OCCR_HS);
            alarm.setAlarmCode(TsiAlarmConfigVo.SYS_00);
            alarm.setAlarmTarget(applicationName);
            alarm.setAlarmValue("Running");
            tsiDatabaseService.insertAlarmOccrHs(alarm);
            tsiDatabaseService.updateProcessState(0);
        }
        catch(Exception e) {
            // no logging
        }
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        int serverId = 0;
        try {
            TsiCvimServerConfig config = (TsiCvimServerConfig) AppUtils.getBean(TsiCvimServerConfig.class);
            config.setStartup(false);
            serverId = config.getServerId();
        } catch (Exception e) { }

        try {
            TsiSessionManager sessionManager = (TsiSessionManager) AppUtils.getBean(TsiSessionManager.class);
            sessionManager.stop();
        } catch (Exception e) { }

        try {
            TsiCvimServer cvimServer = (TsiCvimServer)AppUtils.getBean(TsiCvimServer.class);
            cvimServer.stop();
        } catch (Exception e) { }

        try {
            KafkaProducerService kafkaProducerService = (KafkaProducerService)AppUtils.getBean(KafkaProducerService.class);
            kafkaProducerService.shutdown();
        } catch (Exception e) { }

        try {
            KafkaConsumerService kafkaConsumerService = (KafkaConsumerService)AppUtils.getBean(KafkaConsumerService.class);
            kafkaConsumerService.shutdown();
        } catch (Exception e) { }

        try {
            TsiDatabaseService tsiDatabaseService = (TsiDatabaseService)AppUtils.getBean(TsiDatabaseService.class);
            // 노드 통신상태 Off 초기화
            tsiDatabaseService.updateNodeStatusTerm(serverId);

            // 시스템 종료 알람 이력 저장
            AlarmOccrVo alarm = new AlarmOccrVo(AbstractDbmsVo.DBMS_ALARM_OCCR_HS);
            alarm.setAlarmCode(TsiAlarmConfigVo.SYS_00);
            alarm.setAlarmTarget(applicationName);
            alarm.setAlarmValue("Terminated");
            tsiDatabaseService.insertAlarmOccrHs(alarm);
            tsiDatabaseService.updateProcessState(2);
        } catch (Exception e) { }

        log.error("Application Terminated: {}, {}", sdfDate.format(new Date()), contextClosedEvent.toString());
    }

    @Override
    public void destroy() throws Exception {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }
}
