import StartSceneBase from "../../libs/new_wx/components/StartSceneBase";
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, isAllLevelPass } from "./level";
import Panel from "../../libs/new_wx/components/Panel";
import PanelCtrl from "../../libs/new_wx/ctrls/panelCtrl";
import wait from "../../libs/new_tc/wait";

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();
        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);
    }

    // async initJoker(joker: eui.Image) {
    //     const freq = 3000*2;
    //     egret.Tween.get(joker)
    //         .to({ rotation: -40 }, freq/2, egret.Ease.quadInOut);
    //     await wait(freq/2);
    //     egret.Tween.get(joker, { loop: true })
    //         .to({ rotation: 40 }, freq, egret.Ease.quadInOut)
    //         .to({ rotation: -40 }, freq, egret.Ease.quadInOut);
    // }

    _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);
        });
    }

    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) {
        super.onTap_startBtn(e);
        this['startBtnBg'].visible = false;
        this['startBtn'].visible = false;
        this['countTxt'].visible = false;
        createItems(this);
    }

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