package com.sencorsta.rabs.ui.robot;

import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class RobotUtil {
    public static boolean isCommentMatched(String comment, String searchText) {
        // 检查输入的 searchText 是否是合法的正则表达式
        if (!isValidRegex(searchText)) {
            return false;
        }
        // 将 searchText 编译为正则表达式
        Pattern pattern = Pattern.compile(searchText, Pattern.CASE_INSENSITIVE);
        // 创建 Matcher 对象，使用 comment 进行匹配
        Matcher matcher = pattern.matcher(comment);
        // 查找输入中是否存在与正则表达式匹配的文本
        return matcher.find();
    }

    public static boolean isValidRegex(String regex) {
        try {
            Pattern.compile(regex);
            return true;
        } catch (PatternSyntaxException e) {
            return false;
        }
    }

    public static Mat getWindowMat(Rectangle rectangle) throws AWTException {
        BufferedImage screenCapture = new Robot().createScreenCapture(rectangle);
        return bufferedImageToMat(screenCapture);
    }

    public static Rectangle getRectangle(String windowTitle) {
        WinDef.HWND windowHandle = User32.INSTANCE.FindWindow(null, windowTitle);
        WinDef.RECT rect = new WinDef.RECT();
        User32.INSTANCE.GetWindowRect(windowHandle, rect);
        return new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
    }

    public static Mat bufferedImageToMat(BufferedImage bufferedImage) {
        try {
            // Convert BufferedImage to byte array
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
            byte[] imageBytes = byteArrayOutputStream.toByteArray();

            // Convert byte array to Mat
            MatOfByte matOfByte = new MatOfByte(imageBytes);
            Mat mat = Imgcodecs.imdecode(matOfByte, Imgcodecs.IMREAD_UNCHANGED);

            return mat;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}
