package com.its.safe;

import com.its.app.AppUtils;
import com.its.app.utils.OS;
import com.its.app.utils.SysUtils;
import com.its.safe.config.ApplicationConfig;
import com.its.safe.config.DebugConfig;
import com.its.safe.entity.its.TbUnitSyst;
import com.its.safe.process.DbmsDataProcess;
import com.its.safe.service.UnitSystService;
import com.its.safe.service.VmsSafeAdapterService;
import com.its.safe.ui.JTextAreaOutputStream;
import com.its.safe.ui.MainUI;
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.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableAsync;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.charset.Charset;

@Slf4j
@EnableAsync
@Configuration
@SpringBootApplication
@ComponentScan(basePackages = {"com.its.safe.config", "com.its.safe.dao.mapper", "com.its"})
public class VmsSafeAdapterServerApplication implements CommandLineRunner, ApplicationListener<ContextClosedEvent>, InitializingBean, DisposableBean {

    private static String applicationName = "vms-safe-adapter";

    public static void main(String[] args) {
        System.setProperty("file.encoding", "UTF-8");
        try {
            Field charset = Charset.class.getDeclaredField("defaultCharset");
            charset.setAccessible(true);
            charset.set(null,null);
        } catch(Exception e){
        }

        File file1 = new File("./conf/" + applicationName + ".pid");
        if (file1.exists()) {
            log.error("Program Already Running.....");
        }

        if (OS.isWindows()) {
            ApplicationContext context = new SpringApplicationBuilder(VmsSafeAdapterServerApplication.class)
                    //.web(WebApplicationType.NONE)
                    .listeners(new ApplicationPidFileWriter("./conf/" + applicationName + ".pid"))
                    .headless(false)
                    .bannerMode(Banner.Mode.OFF)
                    .run(args);
        } else {
            SpringApplication application = new SpringApplicationBuilder()
                    .sources(VmsSafeAdapterServerApplication.class)
                    .listeners(new ApplicationPidFileWriter("./conf/" + applicationName + ".pid"))
                    .build();
            application.setBannerMode(Banner.Mode.OFF);
            application.run(args);
        }
    }

    @Override
    public void run(String... args) throws Exception {

        ApplicationConfig applicationConfig = (ApplicationConfig) AppUtils.getBean(ApplicationConfig.class);

        if (OS.isWindows()) {
            String sysTime = SysUtils.getSysTimeStr();
            //JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame(applicationConfig.getName() + " - [" + sysTime + "]");
            MainUI UI = new MainUI(frame);
            SwingUtilities.invokeLater(() -> {
                try {
                    ClassPathResource file = new ClassPathResource("static/image/application.png");
                    URL imgURL = file.getURL();
                    frame.setIconImage(new ImageIcon(imgURL).getImage());
                } catch (IOException e) {
                    log.error("Not found application icon image");
                }
                frame.setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
                frame.setContentPane(UI.getRootPanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent e) {
                        if (JOptionPane.showConfirmDialog(UI.getRootPanel(), applicationConfig.getName() + " 프로그램을 종료 하시겠습니까?", "프로그램 종료", 0) == 0) {
                            System.exit(0);
                        } else {
                            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                        }
                    }
                });
                frame.pack();
                frame.setBounds(100, 100, 900, 600);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                JTextArea logArea = UI.getTaLog();
                logArea.setText(null);
                JTextAreaOutputStream out = new JTextAreaOutputStream(logArea);
                System.setOut(new PrintStream(out));
            });
        }

        log.info("");
        log.info("");
        log.info("************************************************************************************");
        log.info("**                                                                                **");
        log.info("**                         Intelligent Traffic System                             **");
        log.info("**                      VMS Safe Adapter Server Program.                          **");
        log.info("**                                                                                **");
        log.info("**                                                                   [ver.1.0]    **");
        log.info("**          {}", applicationConfig.getId());
        log.info("** startup: {}", applicationConfig.getBootingDateTime());
        log.info("************************************************************************************");

        // init application
        DbmsDataProcess dbmsDataProcess = (DbmsDataProcess)AppUtils.getBean(DbmsDataProcess.class);
        dbmsDataProcess.run();

        UnitSystService unitSystService = (UnitSystService)AppUtils.getBean(UnitSystService.class);
        unitSystService.loadMaster();
        unitSystService.updateUnitSystStts(true);
        TbUnitSyst unit = unitSystService.getDataMap().get(applicationConfig.getId());
        if (unit != null) {
            applicationConfig.setListenPort(unit.getPrgmPort());
        }

        VmsSafeAdapterService vmsSafeAdapterService = (VmsSafeAdapterService)AppUtils.getBean(VmsSafeAdapterService.class);
        vmsSafeAdapterService.run();

//        BisAgipService bisAgipService = (BisAgipService)AppUtils.getBean(BisAgipService.class);
//        Location from = Location.builder()
//                .mLatitude(128.74352336)
//                .mLongitude(36.56392018)
//                .build();
//        NearNodeDto fNode = bisAgipService.getNearNode(from);
//        log.info("From NearNode: {}", fNode);
//
//        Location to = Location.builder()
//                .mLatitude(128.73881251)
//                .mLongitude(36.56128759)
//                .build();
//        NearNodeDto tNode = bisAgipService.getNearNode(to);
//        log.info("  To NearNode: {}", tNode);
//
//        TbLinkDto link = bisAgipService.getSectInfo(fNode.getNodeId(), tNode.getNodeId());
//        log.info("Matching Link: {}", link);

        DebugConfig debugConfig = (DebugConfig)AppUtils.getBean(DebugConfig.class);
        debugConfig.loadDebugInfo();

        // schedule enable
        applicationConfig.setStartSchedule(true);
    }

    public void terminateApplication() {
        UnitSystService unitSystService = (UnitSystService) AppUtils.getBean(UnitSystService.class);
        unitSystService.updateUnitSystStts(false);
    }
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.error("Application Terminated: {}", event.getTimestamp());
        terminateApplication();
    }
    @Override
    public void afterPropertiesSet() throws Exception {
    }
    @Override
    public void destroy() throws Exception {
    }

}
