package com.example.jmacro.wjdr;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.jmacro.wjdr.base.ScreenRect;
import com.example.jmacro.wjdr.task.TaskMineAttack;
import com.example.jmacro.wjdr.task.TaskMining;
import com.example.jmacro.wjdr.task.TaskRewards;
import com.example.jmacro.wjdr.util.Capture;
import com.example.jmacro.wjdr.util.Logger;
import com.example.jmacro.wjdr.util.TaskUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.URL;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 主线程
 *
 * @author wangbing
 * @version 0.0.1
 * @since 1.8
 */
public class MainTask extends JFrame {

    /**
     * 脚本线程
     */
    private static ScheduledFuture<?> schedule;

    /**
     * 工作开始时间
     */
    private final String workStart = "08:00:00";

    /**
     * 工作结束时间
     */
    private final String workEnd = "24:00:00";

    private boolean noDelay = true;

    /**
     * 脚本对象
     */
    private JMacro jMacro;

    /**
     * 主屏幕区域
     */
    private ScreenRect gameScreen;

    public void start() throws AWTException {
        // 加载主题
        try {
            org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 设置标题
        setTitle("无限工具");
        // 设置图标
        URL icon = this.getClass().getClassLoader().getResource("icon.png");
        setIconImage(ImgUtil.read(icon));
        // 脚本初始化
        Logger.info("初始化脚本");
        jMacro = new JMacro(new File("legend"));
        // 设置窗口的宽度和高度
        setSize(400, 300); // 设置窗口的宽度为400像素，高度为300像素
        // 添加一个标签作为示例内容
        JButton button = new JButton();
        button.setText("采图");
        button.setSize(100, 40);
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (gameScreen == null) {
                    Logger.error("请等待窗口定位");
                    return;
                }
                try {
                    new Capture(gameScreen.getLeft(), gameScreen.getTop(), new File("legend"));
                } catch (AWTException awtException) {
                    awtException.printStackTrace();
                }
            }
        });
        getContentPane().add(button);
        // 设置窗口关闭时的操作
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 启动后台线程
        startBack();
        center();
        // 显示窗口
        setVisible(true);
    }

    /**
     * 居中
     */
    private void center() {
        // 获取屏幕尺寸
        java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // 获取窗口尺寸
        java.awt.Dimension frameSize = getSize();
        // 计算窗口居中位置
        setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    }

    /**
     * 后台线程
     */
    public void startBack() {
        Logger.setDebug(true);

        new Thread(() -> {
            while (true) {
                ThreadUtil.sleep(1000);

                // 立即执行
                if (noDelay) {
                    if (schedule != null) {
                        schedule.cancel(true);
                    }

                    noDelay = false;
                    Logger.info("启动线程");
                    schedule = TaskUtil.schedule(new MacroThread(jMacro), 0, TimeUnit.SECONDS);
                    continue;
                }
                if (schedule != null) {
                    continue;
                }

                if (DateUtil.isIn(DateUtil.date(), DateUtil.parse(workStart), DateUtil.parse(workEnd))) {
                    int delay = RandomUtil.randomInt(5, 20);
                    Logger.info("等待{}分钟后，重新启动线程", delay);
                    schedule = TaskUtil.schedule(new MacroThread(jMacro), delay, TimeUnit.MINUTES);
                }
            }
        }).start();
    }

    /**
     * 主线程实现
     */
    public class MacroThread extends JMacroThread {

        public MacroThread(JMacro jMacro) {
            super(jMacro);
        }

        @Override
        public void run() {
            // 定位mumu bar
            Logger.info("定位慕慕窗口");
            ScreenRect mumu = jMacro.findPic("慕慕_工具栏", 0.95d);
            if (mumu == null) {
                throw new IllegalStateException("未检测到MuMu，请开启MuMu模拟器");
            }
            Logger.info("定位慕慕窗口成功");
            // 计算应用窗口返回
            gameScreen = new ScreenRect();
            gameScreen.setLeft(mumu.getLeft() - 428);
            gameScreen.setTop(mumu.getBottom() + 7);
            gameScreen.setRight(mumu.getRight());
            gameScreen.setBottom(mumu.getBottom() + 951);
            Logger.info("应用窗口位置：" + gameScreen.toString());
            Logger.info("应用窗口大小：{}x{}", gameScreen.getRight() - gameScreen.getLeft(), gameScreen.getBottom() - gameScreen.getTop());
            // 获取启动图标
            Logger.info("定位启动图标");
            ScreenRect launch = jMacro.waitAndFindPic(gameScreen, "启动图标", 0.8);
            if (launch != null) {
                Logger.info("启动图标坐标：", launch.toString());
                Logger.info("启动程序");
                jMacro.delay();
                jMacro.mouseLeftClick(launch);
            } else {
                Logger.info("启动图标失败，继续定位主界面");
            }
            Logger.info("定位主界面");
            ScreenRect 城镇 = TaskUtil.timeTask(() -> {
                while (true) {
                    jMacro.delay();
                    { // 定位弹框，关闭弹框
                        Logger.info("检测到广告弹框");
                        ScreenRect rect = jMacro.matchPic(gameScreen, "城镇_充值_L448,36", 0.8d);
                        if (rect != null) {
                            jMacro.mouseLeftClick(rect);
                            Logger.info("检测到广告弹框，关闭弹框");
                        }
                    }

                    jMacro.delay();
                    { // 定位离线收益弹框，关闭弹框
                        ScreenRect rect = jMacro.matchPic(gameScreen, "城镇_离线收益_L204,734", 0.9);
                        if (rect != null) {
                            jMacro.mouseLeftClick(rect);
                            Logger.info("检测到离线收益弹框，关闭弹框");
                        }
                    }

                    jMacro.delay();
                    // 定位主程序
                    ScreenRect rect = jMacro.matchPic(gameScreen, "野外_L444,888", 0.9);
                    if (rect != null) {
                        Logger.info("程序主界面已就绪");
                        return rect;
                    }
                }
            }, 30, TimeUnit.SECONDS);

            if (城镇 == null) {
                schedule.cancel(true);
                schedule = null;
                Logger.info("未扫描到主界面：退出线程");

                return;
            }

            Logger.info("进入主界面");

            Logger.info("进入任务线程");
            TaskUtil.timeTask((Runnable) () -> {
                while (true) {

                    // 矿场攻击检测任务
                    jMacro.delayNormal();
                    new TaskMineAttack(jMacro, gameScreen).run();

                    // 矿场攻击检测任务
                    jMacro.delayNormal();
                    new TaskRewards(jMacro, gameScreen).run();

                    // 自动采矿任务
                    jMacro.delayNormal();
                    new TaskMining(jMacro, gameScreen).run();

                }
            }, 10, TimeUnit.MINUTES);
        }
    }

    /**
     * 启动入口
     */
    public static void main(String[] args) throws AWTException {
        new MainTask().start();
    }
}
