package com.sencorsta.rabs;

import cn.hutool.core.date.DateUtil;
import com.sencorsta.rabs.config.AppConfig;
import com.sencorsta.rabs.obj.ThemeOption;
import com.sencorsta.rabs.obj.ai.AiManage;
import com.sencorsta.rabs.ui.RootFrame;
import org.apache.commons.io.output.TeeOutputStream;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.util.Date;
import java.util.Objects;

/**
 * @author daibin
 */
public class AppMain {
    public static ImageIcon icon;
    //	public static ImageIcon scroll_down = new ImageIcon(Objects.requireNonNull(AppMain.class.getResource("/scroll_down_dark.png")));
//	public static ImageIcon stop_dark = new ImageIcon(Objects.requireNonNull(AppMain.class.getResource("/stop_dark.png")));
    public static RootFrame frame;

    public static void main(String[] args) {
        System.load(System.getProperty("user.dir") + "\\opencv\\x64\\opencv_java490.dll");
        setLog();
        URL resource = AppMain.class.getResource("/icon.png");
        icon = new ImageIcon(Objects.requireNonNull(resource));
        try {
            String appTheme = AppConfig.getInstance().getSetting().getStr("appTheme", ThemeOption.DARCULA.getText());
            LookAndFeel newLookAndFeel = ThemeOption.getLookAndFeel(ThemeOption.fromString(appTheme));
            UIManager.setLookAndFeel(newLookAndFeel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // create frame
        update();

        Long lastUpdateTime = AppConfig.getInstance().getSetting().getLong("lastUpdateTime", "robot", 0L);
        if (!DateUtil.isSameDay(new Date(), new Date(lastUpdateTime))) {
            AppConfig.getInstance().getSetting().clear("dailyTasks");
            AppConfig.getInstance().getSetting().setByGroup("lastUpdateTime", "robot", System.currentTimeMillis() + "");
            AppConfig.getInstance().saveAll();
        }
    }

    private static void setLog() {
		try {
			// 创建一个 File 对象，指定要写入的文件路径和文件名
			File file = new File("runtime.log");

			// 创建一个 FileOutputStream 对象，将它的输出流连接到文件对象的输出流上
			FileOutputStream fos = new FileOutputStream(file);

			// 创建一个 TeeOutputStream 对象，将它的输出流连接到控制台输出流和 FileOutputStream 对象的输出流上
			TeeOutputStream tos = new TeeOutputStream(System.out, fos);

			// 创建一个 PrintStream 对象，将它的输出流连接到 TeeOutputStream 对象的输出流上
			PrintStream printStream = new PrintStream(tos);

			// 使用 System.setOut() 方法将控制台输出流重定向到 PrintStream 对象的输出流上
			System.setOut(printStream);

			// 使用 System.setErr() 方法将标准错误输出流重定向到 PrintStream 对象的输出流上
			System.setErr(printStream);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

    }

    public static void update() {
        RootFrame old = frame;
        if (old != null) {
            old.setVisible(false);
            old.dispose();
        }
        frame = new RootFrame();
        // 设置默认关闭操作
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setIconImage(icon.getImage());
        Integer windowX = AppConfig.getInstance().getSetting().getInt("windowX", 0);
        Integer windowY = AppConfig.getInstance().getSetting().getInt("windowY", 0);
        Integer windowWidth = AppConfig.getInstance().getSetting().getInt("windowWidth", 1024);
        Integer windowHeight = AppConfig.getInstance().getSetting().getInt("windowHeight", 768);
        Integer extendedState = AppConfig.getInstance().getSetting().getInt("extendedState", 0);
        // show frame
        frame.pack();
//		 frame.setLocationRelativeTo(null);
        frame.setSize(windowWidth, windowHeight);
        frame.setLocation(windowX, windowY);
        frame.setExtendedState(extendedState);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                AiManage.getInstance().save();


                // 执行需要在窗口关闭之前执行的操作
                AppConfig.getInstance().getSetting().set("windowX", String.valueOf(frame.getLocation().x));
                AppConfig.getInstance().getSetting().set("windowY", String.valueOf(frame.getLocation().y));
                AppConfig.getInstance().getSetting().set("windowWidth", String.valueOf(frame.getSize().getWidth()));
                AppConfig.getInstance().getSetting().set("windowHeight", String.valueOf(frame.getSize().getHeight()));
                AppConfig.getInstance().getSetting().set("extendedState", String.valueOf(frame.getExtendedState()));
                AppConfig.getInstance().saveAll();
                // 关闭窗口
                frame.dispose();
                System.out.println("程序正常关闭 = " + e);
                System.exit(0);

            }
        });
    }

}
