const { ccclass, property } = cc._decorator;

@ccclass
export default class KeyBoard extends cc.Component {
    @property(cc.Node)
    btnScreenLeft: cc.Node = null;
    @property(cc.Node)
    btnScreenRight: cc.Node = null;

    public static Instance: KeyBoard;

    onLoad() {
        KeyBoard.Instance = this;
        this.btnScreenLeft.on(cc.Node.EventType.TOUCH_START, this.onClick_btnScreenLeft.bind(this));
        this.btnScreenRight.on(cc.Node.EventType.TOUCH_START, this.onClick_btnScreenRight.bind(this));
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    onDestroy() {
        if (KeyBoard.Instance == this) KeyBoard.Instance = null;
        cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    onClick_btnScreenLeft() {
        this.controlBoy(cc.macro.KEY.a);
    }

    onClick_btnScreenRight() {
        this.controlBoy(cc.macro.KEY.d);
    }

    onKeyDown(e: cc.Event.EventKeyboard) {
        this.controlBoy(e.keyCode);
    }

    controlBoy(keyCode: cc.macro.KEY) {
        let boy = window.boy;
        let gm = window.gm;
        if (!boy || !boy.isValid || gm.isGameOver) return;
        switch (keyCode) {
            case cc.macro.KEY.a:
                boy.leftUp();
                break;
            case cc.macro.KEY.w:
                boy.up();
                break;
            case cc.macro.KEY.d:
                boy.rightUp();
                break;
            case cc.macro.KEY.j:
                boy.attack();
                break;
            case cc.macro.KEY.k:
                boy.autoAttack();
                break;
            case cc.macro.KEY.q:
                boy.forward(-1);
                break;
            case cc.macro.KEY.e:
                boy.forward(1);
                break;
            case cc.macro.KEY.r:
                boy.jump();
                break;
            case cc.macro.KEY.t:
                boy.cancelRun();
                break;
        }
    }
}
