package com.utic.center.utic.ptis.server;

import com.utic.center.common.spring.SpringUtils;
import com.utic.center.common.utils.ApplicationUtils;
import com.utic.center.utic.ptis.server.config.ApplicationConfig;
import com.utic.center.utic.ptis.server.controller.UticPtisServerController;
import com.utic.center.utic.ptis.server.service.ProcessStateService;
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.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@SpringBootApplication
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.utic.center.common.spring", "com.utic.center.utic.ptis.server.config", "com.utic.center.utic.ptis.server", "com.utic.center.common.aspect"})
public class UticPtisServerApplication implements CommandLineRunner, ApplicationListener<ContextClosedEvent>, InitializingBean, DisposableBean {

    private static boolean isTerminal = false;
    public static final String APPLICATION_NAME = "utic-ptis-server";

    public static void main(String[] args) {
        Path pidPath = ApplicationUtils.getApplicationPidPath(UticPtisServerApplication.class, APPLICATION_NAME);
        if (ApplicationUtils.isRunning(pidPath)) {
            log.warn("UticPtisServerApplication is already running. Check the PID file: {}", pidPath);
            System.exit(1);
        }

        SpringApplication application = new SpringApplicationBuilder()
                .sources(UticPtisServerApplication.class)
                .listeners(new ApplicationPidFileWriter("./conf/" + APPLICATION_NAME + ".pid"))
                .registerShutdownHook(true)
                .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("**                        UTIC Center PTIS System                                 **");
        log.info("**                  UTIC Center PTIS ETLP Server Program.                         **");
        log.info("**                                                                                **");
        log.info("**                                                                   [ver.1.0]    **");
        log.info("** startup: {}", sdfDate.format(new Date()));
        log.info("************************************************************************************");

        ApplicationConfig applicationConfig = SpringUtils.getBean(ApplicationConfig.class);
        applicationConfig.setStartSchedule(false);

        UticPtisServerController ptisServerController = SpringUtils.getBean(UticPtisServerController.class);
        if (!ptisServerController.initialize()) {
            log.error("UticPtisServerController.initialize: Failed. program shutdown.");
            SpringApplication.exit(SpringUtils.getApplicationContext());
            System.exit(0);
            return;
        }

        // 프로세스 상태 저장
        ProcessStateService processStateService = SpringUtils.getBean(ProcessStateService.class);
        processStateService.processStart();

        applicationConfig.setStartSchedule(true);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.error("on shutdown hook.");
            applicationConfig.setStartSchedule(false);
            terminate();
            try {
                Path pidPath = ApplicationUtils.getApplicationPidPath(UticPtisServerApplication.class, APPLICATION_NAME);
                Files.deleteIfExists(pidPath);
            } catch (IOException ignored) {
            }
        }));

    }

    public void terminate() {
        if (!isTerminal) {
            isTerminal = true;
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            log.error("************************************************************************************");
            log.error("**    Application Terminated: {}", sdfDate.format(new Date()));
            try {
                ApplicationConfig applicationConfig = SpringUtils.getBean(ApplicationConfig.class);
                applicationConfig.setStartSchedule(false);

                ProcessStateService processStateService = SpringUtils.getBean(ProcessStateService.class);
                processStateService.processStop();
            } catch (Exception e) {
                log.error("**    Application Terminated: {}", e.getMessage());
            }
            log.error("************************************************************************************");
        }
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        log.error("{}", contextClosedEvent);
        terminate();
    }

    @Override
    public void destroy() throws Exception {
        log.error("Application destroy");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("Application afterPropertiesSet");
    }
}
