import { GamePlayModel } from "../../libs/tw/model/game/GamePlayModel";
import { getResPath } from "../utils";
import Scene from "../views/Scene";
import Box from "./Box";
import BoxType from "./BoxType";
import Monkey from "./Monkey";
import { NetManager } from "../../libs/tw/manager/NetManager";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";

const { TouchEvent } = egret;
export default class StartScene extends Scene {

    private _monkey: Monkey;
    private _shape: egret.Shape;
    async start(data?) {
        const picData: any = await this.getBg();
        const pic = new egret.Bitmap(picData);
        this.addChild(pic);

        const box = new Box(BoxType.coin);
        this.addChild(box);
        box.x = box.stage.stageWidth / 2;
        box.y = box.stage.stageHeight / 2;
        await box.createBg();

        const monkey = new Monkey();
        this.addChild(monkey);
        monkey.startShaking();
        monkey.addEventListener('pointUpdate', this.onPointUpdate, this)
        monkey.x = 369;
        monkey.y = 70;
        this._monkey = monkey;

        if (window['debug']) {
            this._shape = new egret.Shape();
            this.addChild(this._shape);
        }

        const model = new GamePlayModel();
        model.update();

        box.touchEnabled = true;
        box.addEventListener(egret.TouchEvent.TOUCH_BEGIN, () => {
            NetManager.ins.getInfo(() => {
                model.doStart(() => {
                    model.submit(() => { }, window['boxmap'][box.type])
                }, false);
            });
            NetManager.ins.getRule(() => {
                PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
            })
        }, this);
    }

    onPointUpdate(e: egret.Event) {
        const point = e.data as egret.Point;
        if (window['debug']) {
            this._shape.graphics.clear();
            this._shape.graphics.beginFill(0xff0000);
            const size = window['moneyHandSize'];
            const x = point.x + this._monkey.x;
            const y = point.y + this._monkey.y;
            this._shape.graphics.drawRect(x - size / 2, y - size / 2, size, size);
            this._shape.graphics.endFill();
        }
    }
    async getBg() {
        let url = getResPath() + 'resource/assets/startScene/bg.jpg';
        return new Promise((resolve) => {
            RES.getResByUrl(url, (picData) => {
                resolve(picData)
            }, this, RES.ResourceItem.TYPE_IMAGE);
        });
    }

    protected get skinKey() { return 'Start' }
}