import {
    _decorator, EventKeyboard, Input, input, KeyCode, director,
} from "cc";

import { Snake } from "./Snake";
import { Joystick } from "./Components/Joystick";
import { FastBtn } from "./Components/FastBtn";
import { Events, GameState } from "./Common/Enums";
import { MainGame } from "./MainGame";

const { ccclass, property } = _decorator;

@ccclass("Player")
export class Player extends Snake {

    @property(Joystick)
    joystick: Joystick = null;

    @property(FastBtn)
    fastBtn: FastBtn = null;

    get length(): number {
        return super.length;
    }

    set length(value: number) {
        super.length = value;
        this.updateLength(value);
    }

    onLoad() {
        super.onLoad();
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
        this.fastBtn.node.on("fast", this.onFast, this);
    }

    onDestroy() {
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
        this.fastBtn.node.off("fast", this.onFast, this);
    }

    onFast(isFast: boolean) {
        this.isFast = isFast;
    }

    updateLength(length: number) {
        MainGame.ins.lengthTxt.string = `${length}`;
    }

    death() {
        super.death();

        // 发送游戏结束事件
        director.emit(Events.setGameState, GameState.OVER);
    }

    keyArr: number[] = [];

    onKeyDown(event: EventKeyboard) {

        const keyArr = [KeyCode.KEY_W, KeyCode.KEY_S, KeyCode.KEY_A, KeyCode.KEY_D,];

        if (keyArr.indexOf(event.keyCode) > -1) {
            this.keyArr.push(event.keyCode);
        }

        if (event.keyCode == KeyCode.SPACE) {
            this.fastBtn.isFast = true;
        }

        this.setDir();
    }

    onKeyUp(event: EventKeyboard) {
        const index = this.keyArr.indexOf(event.keyCode);
        if (index > -1) {
            this.keyArr.splice(index, 1);
        }

        if (event.keyCode == KeyCode.SPACE) {
            this.fastBtn.isFast = false;
        }
        this.setDir();
    }

    setDir() {
        if (!this.keyArr.length) return;
        this.joystick.angle = {
            [KeyCode.KEY_W]: 270,
            [KeyCode.KEY_S]: 90,
            [KeyCode.KEY_A]: 180,
            [KeyCode.KEY_D]: 0,
        }[this.keyArr[this.keyArr.length - 1]];
    }

    onUpdate(dt: number) {
        this.setAngle((360 - this.joystick.angle) % 360);
        super.onUpdate(dt);
    }

}
