
import { _decorator, Component, Node, view, macro, v3, Vec3, EventTouch } from 'cc';
import { Tools } from '../common/Tools';
import { weiSan } from '../common/weiSanTools';
import { GameCtrl, GameState } from '../ctrl/GameCtrl';
import { EventData, EventManager } from '../manager/EventManager';
import { UIManager } from '../manager/UIManager';
import { GameModel } from '../model/GameModel';

const { ccclass, property } = _decorator;

@ccclass('MainGame')
export class MainGame extends Component {


    /** 屏幕宽度 */
    gameWidth: number;
    /** 屏幕高度 */
    gameHeight: number;

    onLoad() {

        this.gameWidth = view.getVisibleSize().width;
        this.gameHeight = view.getVisibleSize().height;
        GameModel._ins.mainGame = this;

        this.addTouchEvents();
        this.addInitListener();
    }

    start() {
        this.initGame();
    }

    update(deltaTime: number) {
        // [4]
    }
    /** 触摸开始点坐标 */
    touchStartPos: Vec3;
    /** 触摸事件 监听 */
    addTouchEvents(): void {
        macro.ENABLE_MULTI_TOUCH = false;  //是否开起多点触摸

        this.node.on(Node.EventType.TOUCH_START, this.touchStartBack, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.touchMoveBack, this);
        this.node.on(Node.EventType.TOUCH_END, this.touchEndBack, this);
    };
    /** 触摸开始  回调 */
    touchStartBack(touches: EventTouch) {
        if (!GameCtrl._ins.boolTouch) { return; }
        this.touchStartPos = Tools.getToNodePosForWorld(v3(touches.getUILocation().x, touches.getUILocation().y), this.node);
    }
    /** 触摸移动  回调 */
    touchMoveBack(touches: EventTouch) {
        if (!GameCtrl._ins.boolTouch) { return; }
    }
    /** 触摸结束  回调 */
    touchEndBack(touches: EventTouch) {
        if (!GameCtrl._ins.boolTouch) { return; }
        console.log("boolTouch");
        this.gameEnd();
    }
    /** 初始化游戏 */
    initGame() {
        GameModel._ins.gameScore = 0;
        GameCtrl._ins.initGame();
        GameCtrl._ins.boolTouch = true;
    }
    /** 开始游戏 */
    startGame() {
    }
    /** 游戏结束 */
    gameEnd() {
        if (GameCtrl._ins.gameState == GameState.Over) { return; }
        GameCtrl._ins.overGame();

        weiSan.log("游戏结束");
        this.scheduleOnce(() => {
            UIManager.OpenUI("OverUI");
        }, 0.5);
    };


    /** 事件  监听 */
    addInitListener() {
        EventManager.addListener(EventData.START_GAME, this.startGame.bind(this), this.node);

    }
    onDestroy() {
        EventManager.removeListenerForTarget(this.node);
    }

}

