package com.sencorsta.rabs.ui.robot;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.SystemUtil;
import com.sencorsta.rabs.config.AppConfig;
import com.sencorsta.rabs.obj.ai.AiManage;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @author daibin
 */
public class RobotPanel extends JPanel {
    public boolean isThinking;
    JComboBox<String> windowComboBox = new JComboBox<>();
    private String selectedWindowTitle;
    JButton clearAllData = new JButton("清空数据");
    JButton forcePass = new JButton("跳过场景");
    JButton aiButton = new JButton("开始作业");
    private JTextField regexTextField = new JTextField();
    public static ScheduledThreadPoolExecutor thinkPoll = new ScheduledThreadPoolExecutor(SystemUtil.getTotalThreadCount() * 2 + 1);

    public RobotPanel() {
        setLayout(new BorderLayout());

        JPanel controlPanel = new JPanel(new FlowLayout());
        controlPanel.add(regexTextField);
        controlPanel.add(windowComboBox);
        controlPanel.add(aiButton);
        controlPanel.add(clearAllData);
        controlPanel.add(forcePass);
        add(controlPanel, BorderLayout.NORTH);

        getWindowTitles();
        regexTextField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                getWindowTitles();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                getWindowTitles();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                getWindowTitles();
            }
        });
        aiButton.addActionListener(e -> {
            if (isThinking){
                isThinking=false;
                AiManage.getInstance().stop();
                aiButton.setText("开始作业");
            }else {
                AppConfig.getInstance().getSetting().setByGroup("selectedWindowTitle", "robot", (String) windowComboBox.getSelectedItem());
                AppConfig.getInstance().saveAll();

                AiManage aiManage = AiManage.getInstance();
                aiManage.setWindowName((String) windowComboBox.getSelectedItem());
                aiManage.run();
                isThinking=true;
                aiButton.setText("终止作业");
            }
        });
        clearAllData.addActionListener(e -> {
            if (AiManage.getInstance().isRunning()) {
                AiManage.getInstance().stop();
                aiButton.setText("开始作业");
            }
            AiManage.getInstance().clearAllData();
        });
        forcePass.addActionListener(event -> {
            AiManage.getInstance().forcePass();
        });

        logTextArea = new JTextArea();
        logTextArea.setEditable(false);

        JScrollPane scrollPane = new JScrollPane(logTextArea);
        add(scrollPane, BorderLayout.CENTER);

        redirectSystemStreams();
    }
    private JTextArea logTextArea;
    private void updateTextArea(final String text) {
        SwingUtilities.invokeLater(() -> logTextArea.append(text));
    }

    private PrintStream originalOut = System.out;
    private PrintStream originalErr = System.err;
    private void redirectSystemStreams() {
        OutputStream out = new OutputStream() {
            @Override
            public void write(int b) {
                originalOut.write(b);
                updateTextArea(String.valueOf((char) b));
            }

            @Override
            public void write(byte[] b, int off, int len) {
                originalOut.write(b, off, len);
                updateTextArea(new String(b, off, len));
            }

            @Override
            public void write(byte[] b) {
                write(b, 0, b.length);
            }
        };

        System.setOut(new PrintStream(out, true));
        System.setErr(new PrintStream(out, true));
    }

    private void getWindowTitles() {
        String lastSelect = AppConfig.getInstance().getSetting().getStr("selectedWindowTitle", "robot", "");
        windowComboBox.removeAllItems();
        windowComboBox.addItem("");
        final User32 user32 = User32.INSTANCE;
        user32.EnumWindows((hwnd, pointer) -> {
            char[] buffer = new char[1024];
            user32.GetWindowText(hwnd, buffer, buffer.length);
            String trim = new String(buffer).trim();
            if (StrUtil.isNotBlank(trim)) {
                if (RobotUtil.isCommentMatched(trim, regexTextField.getText())) {
                    windowComboBox.addItem(trim);
                    if (lastSelect.equals(trim)) {
                        windowComboBox.setSelectedItem(trim);
                    }
                }
            }
            return true;
        }, null);
    }
}
