import StartSceneBase from "../../libs/new_wx/components/StartSceneBase";
import DebugRender from "../physics/DebugRender";
import EgretRender from "../physics/EgretRender";
import check from "./check";
import { bubble, bubbleGroup, bubbleMask } from "./collisionConfig";
import createBox from "./createBox";
import createBubblePic from "./createBubblePic";
import createItems from "./createItems";
import random from "./random";
import { startStandbyBubblesLeft, startStandbyBubblesRight, stopStandbyBubblesLeft, stopStandbyBubblesRight } from "./standbyBubbles";
import { playScoreAni } from "./playMovieClip";
import createBtns from "./createBtns";

export default class StartScene extends StartSceneBase {
    _engine: Matter.Engine;
    _egretRender: EgretRender;
    private _debugRender: DebugRender;
    private _lastTimestamp = 0;
    _startStandbyBubblesLeft: number;
    _startStandbyBubblesRight: number;
    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(); // 打开渲染与心跳
        }

        this.addChild(this['basket_bottom']);

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

        //创建egret渲染
        const egretRenderContainer = new egret.Sprite();
        this.addChild(egretRenderContainer);
        this._egretRender = new EgretRender(egretRenderContainer, this._engine);

        this._debugRender = new DebugRender(this._engine);
        // this.addChild(this._debugRender);

        this.addChild(this['basket_top']);
        this.addChild(this['glass']);

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

    addForce = false;
    stageX = 0;
    stageY = 0;
    async runGame() {
        createBox(this);

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

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

        createItems(this);

        Matter.Events.on(this._engine, 'beforeUpdate', () => {
            if (!this.addForce) return
            this.addForce = false;
            const isleft = this.stageX < 375;
            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);
            }
            for (let j = 0; j < 1; j++) {
                const start = isleft ? { x: 208 + 50, y: 821 + 30 } : { x: 549 - 50, y: 821 + 30 };
                const r = random(10, 14);
                const body = this._egretRender.circle(start.x, start.y, r, null,
                    {
                        density: 0.001 * 3,
                        restitution: 1,
                        force: { x: (isleft ? 1 : -1) * 0.02 * 1.7, y: 0 },
                        collisionFilter: { group: bubbleGroup, category: bubble, mask: bubbleMask }
                    }
                );

                setTimeout(() => {
                    this._egretRender.remove(body);
                }, 1000);
            }


            console.log('吹起来');
        });

        [this['leftBtn'], this['rightBtn']].forEach(btn => {
            btn.addEventListener(egret.TouchEvent.TOUCH_TAP, (e: egret.TouchEvent) => {
                this.addForce = true;
                this.stageX = e.stageX;
                if (this.stageX < 375) {
                    stopStandbyBubblesLeft();
                    clearTimeout(this._startStandbyBubblesLeft);
                    this._startStandbyBubblesLeft = setTimeout(() => {
                        startStandbyBubblesLeft(this._egretRender);
                    }, 1000);
                } else {
                    stopStandbyBubblesRight();
                    clearTimeout(this._startStandbyBubblesRight);
                    this._startStandbyBubblesRight = setTimeout(() => {
                        startStandbyBubblesRight(this._egretRender);
                    }, 1000);
                }
                // playScoreAni(this,-1)

            }, this);
        });

        createBtns(this);

        startStandbyBubblesLeft(this._egretRender);
        startStandbyBubblesRight(this._egretRender);
    }

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

    // onGetAward() {
    //     egret.stopTick(this.onTick, this);
    //     setTimeout(() => {
    //         this._lastTimestamp = 0;
    //         this.runEngine();
    //     }, 1000);
    // }

    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);
        // console.log(delta);
        this._debugRender.run();
        this._egretRender.run();
        check(this);
        return false;
    }

    destroy() {
        super.destroy();
    }

}