package com.axis.innovators.box.util;

import com.axis.innovators.box.ui.AIChatDialog;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 支持组合键的全局快捷键注册
 *
 * @author tzdwindows 7
 */
public class GlobalShortcuts {
    private static AIChatDialog aiDialog;
    private static final Map<Set<Integer>, TriggeringEvents> shortcuts = new HashMap<>();
    private static final Set<Integer> pressedKeys = new HashSet<>();
    private static final Set<Set<Integer>> triggeredCombinations = new HashSet<>();

    static {
        Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
        logger.setLevel(Level.WARNING);
        logger.setUseParentHandlers(false);

        try {
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            ex.printStackTrace();
        }

        GlobalScreen.addNativeKeyListener(new NativeKeyListener() {
            @Override
            public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {}

            @Override
            public void nativeKeyPressed(NativeKeyEvent e) {
                int keyCode = e.getKeyCode();
                pressedKeys.add(keyCode);
                checkCombinations();
            }

            @Override
            public void nativeKeyReleased(NativeKeyEvent e) {
                int keyCode = e.getKeyCode();
                pressedKeys.remove(keyCode);
                // 释放任意键时重置触发状态
                triggeredCombinations.clear();
            }
        });

        // 注册关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                GlobalScreen.unregisterNativeHook();
            } catch (NativeHookException ex) {
                ex.printStackTrace();
            }
        }));
    }

    /**
     * 注册组合快捷键
     * @param events 触发事件
     * @param keyCodes 组合键键码（如 NativeKeyEvent.VC_SHIFT, NativeKeyEvent.VC_F12）
     */
    public static void registerShortcut(TriggeringEvents events, int... keyCodes) {
        Set<Integer> combination = new HashSet<>();
        for (int code : keyCodes) {
            combination.add(code);
        }
        shortcuts.put(combination, events);
    }

    // 检查当前按下的键是否匹配任何组合
    private static void checkCombinations() {
        for (Map.Entry<Set<Integer>, TriggeringEvents> entry : shortcuts.entrySet()) {
            Set<Integer> requiredKeys = entry.getKey();
            // 检查是否满足组合键条件且未触发过
            if (pressedKeys.containsAll(requiredKeys) && !triggeredCombinations.contains(requiredKeys)) {
                entry.getValue().triggering();
                triggeredCombinations.add(requiredKeys);
            }
        }
    }

    public interface TriggeringEvents {
        void triggering();
    }

    private static void toggleAIDialog() {
        SwingUtilities.invokeLater(() -> {
            if (aiDialog == null) {
                aiDialog = new AIChatDialog();
            }
            aiDialog.toggleVisibility();
        });
    }

    public static void main(String[] args) throws UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(new com.formdev.flatlaf.FlatDarculaLaf());
        registerShortcut(
                GlobalShortcuts::toggleAIDialog,
                NativeKeyEvent.VC_CONTROL,
                NativeKeyEvent.VC_SHIFT,
                NativeKeyEvent.VC_A
        );
    }
}