import Panel from "../../libs/new_wx/components/Panel";
import StartSceneBase from "../../libs/new_wx/components/StartSceneBase";
import PanelCtrl from "../../libs/new_wx/ctrls/panelCtrl";
import { ModuleTypes } from "../../libs/new_wx/types/sceneTypes";
import EgretRender from "../physics/EgretRender";
import getAngle from "../physics/utils/getAngle";
import getRotation from "../physics/utils/getRotation";
import check from "./check";
import check2 from "./check2";
import createBox from "./createBox";
import createItems from "./createItems";
import { initLevel, resetLevel, updateLevelView, resetData } from "./level";
import { playToastSuccess } from "./playMovieClip";
import doStart from "../../libs/new_tw/ctrls/doStart";
import wait from "../../libs/new_tc/wait";
import { NetManager } from "../../libs/tw/manager/NetManager";

export default class StartScene extends StartSceneBase {
    _engine: Matter.Engine;
    _egretRender: EgretRender;
    private _lastTimestamp = 0;
    _startStandbyBubblesLeft: number;
    _startStandbyBubblesRight: number;
    egretRenderContainer: egret.Sprite;
    _currentDisplay: egret.DisplayObject;

    private removeGuideAndResume() {
        this['guide'].visible = this['tips'].visible = this['tips2'].visible = this['guild2pic'].visible = this['getitBtn'].visible = false;
        this._lastTimestamp = 0;
        egret.ticker.resume(); // 打开渲染与心跳
        this['group'].addChildAt(this.egretRenderContainer, 5);
    }

    onCollision(body: Matter.Body) {
        if (localStorage.getItem('guilde1') == '1') return;
        PanelCtrl.instance.closeCurrent();
        localStorage.setItem('guilde1', '1');
        egret.ticker.pause(); // 关闭渲染与心跳
        this['guide'].visible = this['tips'].visible = true;
        this['group'].addChild(this.egretRenderContainer);
    }

    onCollisionBoom(body: Matter.Body) {
        if (localStorage.getItem('guilde2') == '1') return;
        PanelCtrl.instance.closeCurrent();
        localStorage.setItem('guilde2', '1');
        egret.ticker.pause(); // 关闭渲染与心跳
        this['guide'].visible = this['tips2'].visible = this['guild2pic'].visible = this['getitBtn'].visible = true;
        // this['group'].addChild(this.egretRenderContainer);
    }

    async start(data?) {
        super.start();
        resetData();
        initLevel(this);
        // wait(5000).then(()=>PanelCtrl.instance.addMask());
        egret.lifecycle.onPause = () => {
            console.log("app 进入后台");
            egret.ticker.pause(); // 关闭渲染与心跳
        }
        egret.lifecycle.onResume = () => {
            console.log("app 进入前台");
            if (this['guide'].visible == false) {
                this._lastTimestamp = 0;
                egret.ticker.resume(); // 打开渲染与心跳
            }
        }

        //创建引擎
        const engine = Matter.Engine.create();
        this._engine = engine;

        //创建egret渲染
        this.egretRenderContainer = new egret.Sprite();
        this._egretRender = new EgretRender(this.egretRenderContainer, this._engine);
        this['group'].y = this.stage.stageHeight - 1624;
        this['group'].addChildAt(this.egretRenderContainer, 5);
        this['group'].addChild(this['leftBtn']);
        this['group'].addChild(this['rightBtn']);
        this['group'].addChild(this['guild2pic']);
        this['group'].addChild(this['startBtnBg']);
        this['group'].addChild(this['startBtn']);
        this['group'].addChild(this['countTxt']);
        this['guide'].visible = this['tips'].visible = this['tips2'].visible = this['guild2pic'].visible = this['getitBtn'].visible = false;

        // run the engine
        this.runEngine();

        const options: any = {
            width: 750,
            height: 1624,
            wireframes: !1,
        };

        const render = Matter.Render.create({
            element: document.getElementById('debugCanvas'),
            engine: engine,
            options: options
        });
        Matter.Render.run(render);

        // this.initJoker(this['joker']);
        this.initLights(this['lights1'], this['lights2']);
        this['boomalert'].height = this.stage.stageHeight;
        this.runGame();
    }

    async initLights(img1: eui.Image, img2: eui.Image) {
        img1.alpha = 0;
        img2.alpha = 1;
        const freq = 500;
        egret.Tween.get(img1, { loop: true })
            .set({ alpha: 1 }).wait(freq)
            .set({ alpha: 0 }).wait(freq);
        egret.Tween.get(img2, { loop: true })
            .set({ alpha: 0 }).wait(freq)
            .set({ alpha: 1 }).wait(freq);
    }

    _seesaw: Matter.Body;
    async runGame() {
        const { seesaw } = createBox(this);
        this._seesaw = seesaw;

        const reslist = ['boom', 'gift2', 'candy2',
            'donut',
            'egg',
            'icecream']
        await Promise.all(
            reslist.map(res => RES.getResAsync(`${res}_json`))
        );

        // createItems(this);

        let touchLeft = false;
        let touchRight = false;
        let angle = 0;
        const rotationLimit = 30;
        const ontick = () => {
            if (touchLeft)
                angle += getAngle(-1);
            if (touchRight)
                angle += getAngle(1);
            let rotation = getRotation(angle);
            if (rotation > rotationLimit) {
                rotation = rotationLimit;
                angle = getAngle(rotationLimit);
            }
            if (rotation < -rotationLimit) {
                rotation = -rotationLimit;
                angle = getAngle(-rotationLimit);
            }

            this['joker'].rotation = -rotation;
            Matter.Body.setAngle(seesaw, getAngle(rotation));
            return false;
        }

        [this['leftBtn'], this['rightBtn']].forEach(btn => {
            btn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, (e: egret.TouchEvent) => {
                touchLeft = e.stageX < 375;
                touchRight = !touchLeft;
                ontick();
                egret.startTick(ontick, this);
                if (this['guide'].visible) {
                    this.removeGuideAndResume();
                }
            }, this);
        });

        this['getitBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, (e: egret.TouchEvent) => {
            this.removeGuideAndResume();
        }, this);

        [this['leftBtn'], this['rightBtn']].forEach(btn => {
            btn.addEventListener(egret.TouchEvent.TOUCH_END, (e: egret.TouchEvent) => {
                egret.stopTick(ontick, this);
            }, this);
        });

        PanelCtrl.instance.addEventListener('onPanelRemoved', this.onPanelRemoved, this);

        const createMask = () => {
            const s = new egret.Sprite();
            s.graphics.beginFill(0, 0.7);
            s.graphics.drawRect(0, 0, 750, 1624);
            s.graphics.endFill();
            return s
        }
        this['guide'].addChild(createMask())
        this['startBtnBg'].addChild(createMask())

        this.updateGetInfoView();
        this.updateExemptionTxt();
    }

    async onPanelRemoved(e: egret.Event) {
        const panel = e.data.panel as Panel;
        if (panel.type == ModuleTypes.BoomNoPrizePanel || panel.type == ModuleTypes.BoomPrizePanel) {
            await updateLevelView(false);
            await playToastSuccess(this, 0);
            createItems(this);
        } else if (panel.type == ModuleTypes.CashBigPrize || panel.type == ModuleTypes.CashNoPrizePanel || panel.type == ModuleTypes.CashPrizePanel) {
            resetLevel();
            this['startBtnBg'].visible = this['startBtn'].visible = this['countTxt'].visible = true;
            this.updateStartBtnStatus();
            this.updateCountTxt();
        }
        else if (panel.type == ModuleTypes.ALERT_PANEL) {
            this['startBtnBg'].visible = this['startBtn'].visible = this['countTxt'].visible = true;
            this.updateStartBtnStatus();
            this.updateCountTxt();
        }
    }

    runEngine() {
        egret.startTick(this.onTick, this);
    }

    private onTick(timestamp: number) {
        if (this._lastTimestamp === 0) {
            this._lastTimestamp = timestamp;
            return;
        }
        let delta = timestamp - this._lastTimestamp;
        if (delta > 20)
            delta = 20;
        this._lastTimestamp = timestamp;
        Matter.Engine.update(this._engine, delta);
        this._egretRender.run();
        // this._debugRender.run();
        check(this);
        check2(this);
        return false;
    }

    onTap_startBtn(e?: egret.Event) {
        doStart((success) => {
            if (!success) return;
            wait(1000).then(() => NetManager.ins.getInfo())
            this['startBtnBg'].visible = false;
            this['startBtn'].visible = false;
            this['countTxt'].visible = false;
            createItems(this);
        });

    }

    destroy() {
        super.destroy();
    }
}