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

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;
    async runGame() {
        createBox(this);

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

        createItems(this);

        Matter.Events.on(this._engine, 'beforeUpdate', () => {
            if (!this.addForce) return
            this.addForce = false;
            const scale = 2.2;
            for (let i = 0; i < 11; i++) {
                setTimeout(() => {
                    const r = random(10, 14);
                    const bubblePic = createBubblePic(r);//默认球的尺寸100
                    const start = this.stageX < 375 ? { x: 208, y: 821 } : { x: 549, y: 821 };
                    const basex = 0.01;
                    const fx = this.stageX < 375 ? random(-basex, basex) : random(-basex, basex);
                    const padding = 50;
                    const startx = random(start.x-padding,start.x+padding);
                    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);
            }
            console.log('吹起来');
        });

        this.stage.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);
            }

        }, this);

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

    check() {
        const center = 382;
        const paddingX = 50;
        const ypos = 440;
        const h = 40;
        // this._egretRender._root.graphics.beginFill(0xff0000, 1);
        // this._egretRender._root.graphics.drawRect(center - paddingX, ypos, paddingX * 2, h);
        // this._egretRender._root.graphics.endFill();

        const bodies = Matter.Composite.allBodies(this._engine.world);
        const isAward = (i: Matter.Body) => { return i.collisionFilter.group == award }
        bodies.forEach(i => {
            if (!isAward(i)) return;
            if (i['timer']) {
                const t0 = Date.now() - i['timer'];
                if (t0 > 3000)//3s之内不可再用
                {
                    delete i['timer'];
                    console.log('重新可用', Date.now() / 1000)
                }
            }
            const { x, y } = i.position;
            const xResult = x > (center - paddingX) && x < (center + paddingX);
            const yResult = y > ypos && y < (ypos + h);
            if (xResult && yResult && i.velocity.y > 0 && !i['timer']) {
                i['timer'] = Date.now();
                if (i.label == 'boom') {
                    console.log('boom');
                    this._egretRender.remove(i);
                }
                else {
                    console.log('不是boom，重用', Date.now() / 1000);
                }
                // this.onGetAward();
            }
        })
    }

    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();
        this.check();
        return false;
    }

    destroy() {
        super.destroy();
    }

}