import webview
from yangke.common.config import logger
import yangke.game.ghost.ghostbox as gb
from yangke.common.KeysTransfer import KeysTransfer
from yangke.common.win.mouse_key_hook import MouseKeyManager
from pyWinhook.HookManager import KeyboardEvent
from yangke.base import pic2ndarray, show_pic

km = MouseKeyManager()


def custom_logic(window):
    window.toggle_fullscreen()
    window.evaluate_js('alert("Nice one brother")')


class Api:
    def __init__(self):
        gb.opendevice(0)
        self.keys_transfer = KeysTransfer("js_code", "gb_name")
        self.debugging = False
        self.pressed_key = set()

    def start_debug(self):
        """
        开始调试时，前段会调用该函数，并监听前端界面上的鼠标键盘事件，但全局键盘按键需要由python屏蔽并转发
        """
        logger.debug("开始调试")
        self.shield_win_hotkeys()  # 屏蔽windows全屏热键并转发给应用程序
        self.release_all_keys()
        self.debugging = True

    def stop_debug(self):
        km.stop_shield_keyboard()  # 不在屏蔽系统热键
        self.debugging = False
        logger.debug("结束调试")

    def hook_sys_keyboard(self, event: KeyboardEvent):
        # pywinhook检测到全局热键时的回调函数
        key = event.Key  # pywinhook的键名
        key_js_code = KeysTransfer("pywinhook_name", "js_code").transfer(key)

        if event.MessageName == "key down":
            self.keydown(key_js_code)  # 被屏蔽的win键将不会被发送到窗口中
        elif event.MessageName == "key up":
            self.keyup(key_js_code)
        return False

    def shield_win_hotkeys(self):
        """
        屏蔽windows系统的系统级快捷键
        """
        km.shield_hot_keys(["Win",
                            "PrintScreen",
                            "Win+1",
                            "Win+D",
                            "Win+E",
                            ], self.hook_sys_keyboard)

    def keydown(self, key):
        """
        @param key: js_code的键名
        """
        key = self.keys_transfer.transfer(key)
        if key not in self.pressed_key:
            logger.debug(f"keydown {key}")
            gb.presskeybyname(key)
            self.pressed_key.add(key)

    def keyup(self, key):
        key = self.keys_transfer.transfer(key)
        if key in self.pressed_key:
            logger.debug(f"keyup {key}")
            gb.releasekeybyname(key)
            self.pressed_key.remove(key)

    def mousedown(self, x, y, button):  # 1左键，2中键，3右键
        logger.debug(f"press key {x=}, {y=}, {button=}")
        gb.movemouseto(x, y)
        if gb.getmousex() - x > 3 or gb.getmousey() - y > 3:
            logger.debug(f"矫正鼠标位置 {x=}, {y=}")
            gb.setmouseposition(x, y)
        gb.pressmousebutton(button)

    def mouseup(self, x, y, button):  # 1左键，2中键，3右键
        logger.debug(f"release key {x=}, {y=}, {button=}")
        gb.movemouseto(x, y)
        gb.releasemousebutton(button)

    def mousemove(self, x, y, buttons):
        """
        注意该函数的第三个参数和mousedown与mouseup的意义不同
        :param x:
        :param y:
        :param buttons: 取值1：左键，2：右键，3：左键和右键，4：中键，5：中键和左键，以此类推
        """
        logger.debug(f"move to {x=}, {y=}, {buttons=}")
        gb.movemouseto(x, y)

    @staticmethod
    def release_all_keys():
        gb.releaseallkey()
        gb.releaseallkey()

    def dispatch_snapshot(self, snapshot):
        pic = pic2ndarray(snapshot)
        # logger.debug(f"dispatch snapshot {snapshot=}")
        return True

    def get_snapshot(self):
        window.evaluate_js('alert("Nice one brother")')


if __name__ == '__main__':
    chinese = {
        'global.quitConfirmation': u'确定关闭?',
    }

    api = Api()
    window = webview.create_window(
        title='gf-ui',
        url='./dist/index.html',
        width=2250,
        height=1250,
        resizable=True,  # 固定窗口大小
        text_select=False,  # 禁止选择文字内容
        confirm_close=True,  # 关闭时提示
        js_api=api,  # api中定义供html调用的函数
        min_size=(900, 620)  # 设置窗口最小尺寸
    )

    # 启动窗口
    # webview.start(localization=chinese, http_server=True, debug=True)
    # webview.start(custom_logic, window)  # 传入的函数会被立即执行
    webview.start(localization=chinese, ssl=True, debug=True)  # 该语句会阻塞，直到程序关闭后才会继续执行后续代码
