import { _decorator, Component, director, Node} from 'cc';

import lib from "./Library.js";
import webView from "./WebView.js";
import { find } from 'cc';
import { GameEventEnum } from '../../Game/GameStruct';
const { ccclass, property } = _decorator;

@ccclass('WebViewListener')
export default class WebViewListener extends Component {

    public static Init(): WebViewListener {
        if (!lib.openInWebview()) return null;
        let node = new Node(this.name);
        let comp = node.addComponent(WebViewListener);
        director.getScene().addChild(node);
        return comp;
    }
    
    protected onLoad(): void {
        console.log("WebViewListener onLoad");
        webView.init(this.node);
        webView.onAddQuitModalListener();
        webView.onBindBoxingPost();
        this.node.on('onGameInit', this._onGameInit, this);
        this.node.on("onBoxingPostHit", this._onBoxingPostHit, this);
        this.node.on("onQuitModal", this._onQuitModal, this);
    }

    protected onDestroy(): void {
        webView.unRegister(this.node);
    }

    private _onGameInit(gameData) {
        window.gm.node.emit(GameEventEnum.UniAppGameInit, {
            nickname: gameData.userName,
            gender: gameData.gender,
            avatarUrl: gameData.avatarBase64Url,
        });
    }

    private _onBoxingPostHit(data) {
        if (data.sendType == "hotman") {
            let gameModeView = find("Canvas-001/GameModeView");
            if (gameModeView.active) gameModeView.emit(Node.EventType.TOUCH_START);
        }
    }

    private _onQuitModal(data) {
        if (data.data.confirm) webView.closeGame();
    }
}
