const {ccclass, property} = cc._decorator;

import KeyBoard from "../Game/KeyBoard";
import webView = require("./WebView");

@ccclass
export default class WebViewListener extends cc.Component {
    public static Instance: WebViewListener;

    public static Init(): void {
        if (WebViewListener.Instance) return;
        let node = new cc.Node(WebViewListener.name);
        WebViewListener.Instance = node.addComponent(WebViewListener);
        cc.director.getScene().addChild(node);
        cc.game.addPersistRootNode(node);
    }
    
    protected onLoad(): void {
        console.log("WebViewListener onLoad");
        webView.register(this.node);
        webView.onAddQuitModalListener();
        webView.onBindBoxingPost();
        this.node.on("onBoxingPostHit", this.onBoxingPostHit, this);
        this.node.on("onQuitModal", this.onQuitModal, this);
    }

    onBoxingPostHit(data) {
        if (!KeyBoard.Instance) return;
        if (data.sendType == "hotman") {
            if (data.direction == "leftPunch") {
                KeyBoard.Instance.controlBoy(cc.macro.KEY.d);
            } else if (data.direction == "straightPunch") {
                KeyBoard.Instance.controlBoy(cc.macro.KEY.w);
            } else if (data.direction == "rightPunch") {
                KeyBoard.Instance.controlBoy(cc.macro.KEY.a);
            }
        } else if (typeof data.type == "string" && data.sendType == "RopeSkipping") {
            let type: string = data.type;
            if (type.includes("left")) {
                KeyBoard.Instance.controlBoy(cc.macro.KEY.a);
            } else if (type == "normal") {
                KeyBoard.Instance.controlBoy(cc.macro.KEY.w);
            } else if (type.includes("right")) {
                KeyBoard.Instance.controlBoy(cc.macro.KEY.d);
            }
        }
    }

    onQuitModal(data) {
        if (data.data.confirm) webView.closeGame();
    }
}
