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 { award, awardMask } from "./collisionConfig";
import createBox from "./createBox";
import createItems from "./createItems";
import DebugRender from "../physics/DebugRender";

export default class StartScene extends StartSceneBase {
    _engine: Matter.Engine;
    _egretRender: EgretRender;
    // _debugRender:DebugRender;
    private _lastTimestamp = 0;
    _startStandbyBubblesLeft: number;
    _startStandbyBubblesRight: number;
    egretRenderContainer: egret.Sprite;
    async start(data?) {
        super.start();
        egret.lifecycle.onPause = () => {
            console.log("app 进入后台");
            egret.ticker.pause(); // 关闭渲染与心跳
        }
        egret.lifecycle.onResume = () => {
            console.log("app 进入前台");
            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.once(egret.Event.ADDED_TO_STAGE, () => { this['group'].y = this.stage.stageHeight - 1624; }, this);
        this['group'].addChildAt(this.egretRenderContainer, 2);
        // [this['basket_bottom'], this['basket_top'], this['glass']].forEach(item =>
        //     egret.Tween.get(item).set({ alpha: 0 }).to({ alpha: 1 }, 500));

        // 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._debugRender=new DebugRender(this._engine);
        // this['group'].addChild(this._debugRender);

        this.runGame();
    }

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

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

        RES.getResAsync('success_json');
        RES.getResAsync('fail_json');

        createItems(this);

        const ontick = () => {
            const rotationLimit = 30;
            if (touchLeft)
                angle += getAngle(-1);
            if (touchRight)
                angle += getAngle(1);
            let rotation = getRotation(angle);
            if (rotation > rotationLimit) {
                rotation = rotationLimit;
            }
            if (rotation < -rotationLimit) {
                rotation = -rotationLimit;
            }
            Matter.Body.setAngle(seesaw, getAngle(rotation));
            return false;
        }

        let touchLeft = false;
        let touchRight = false;
        let angle = 0;

        this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, (e: egret.TouchEvent) => {
            touchLeft = e.stageX < 375;
            touchRight = !touchLeft;
            ontick();
            egret.startTick(ontick, this);
        }, this);
        this.stage.addEventListener(egret.TouchEvent.TOUCH_END, (e: egret.TouchEvent) => {
            egret.stopTick(ontick, this);
        }, this);

        Matter.Events.on(this._engine, 'beforeUpdate', () => {
            // const isleft = 1;
            // const start = isleft ? { x: 208, y: 821 } : { x: 549, y: 821 };
            // const scale = 2.2;
            // for (let i = 0; i < 15; i++) {
            //     setTimeout(() => {
            //         const r = random(10, 14);
            //         let bubblePic;
            //         bubblePic = createBubblePic(r);//默认球的尺寸100
            //         const basex = 0.02;
            //         const xoffset = 0.007;
            //         const fx = isleft ? random(-basex, basex) : random(-basex, basex);
            //         const padding = 50;
            //         const startx = random(start.x - padding, start.x + padding);
            //         if (fx < -xoffset || fx > xoffset) bubblePic = null;
            //         const body = this._egretRender.circle(startx, start.y, r, bubblePic,
            //             {
            //                 density: 0.001 * 3,
            //                 restitution: 1,
            //                 force: { x: fx * scale, y: -0.02 * scale },
            //                 collisionFilter: { group: bubbleGroup, category: bubble, mask: bubbleMask }
            //             }
            //         );

            //         setTimeout(() => {
            //             this._egretRender.remove(body);
            //         }, 1000);
            //     }, Math.random() * 200);
            // }
        });

        [this['leftBtn'], this['rightBtn']].forEach(btn => {
            btn.addEventListener(egret.TouchEvent.TOUCH_TAP, (e: egret.TouchEvent) => {

            }, 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);
        return false;
    }

    destroy() {
        super.destroy();
    }

}