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

export default class StartScene extends StartSceneBase {
    _engine: Matter.Engine;
    _egretRender: EgretRender;
    private _lastTimestamp = 0;
    _startStandbyBubblesLeft: number;
    _startStandbyBubblesRight: number;
    egretRenderContainer: egret.Sprite;
    score = 10;
    MAX_SCORE = 20;
    private scoreTxt: eui.Label;

    updateProgress() {
        const percent = this.score / this.MAX_SCORE;
        const maxwidth = this.progressfront.width;
        egret.Tween.removeTweens(this.progressfront.mask);
        egret.Tween.get(this.progressfront.mask).to({ width: percent * maxwidth }, 200);
    }

    onBoom(): any {
        this.score = 0;
        this.updateProgress();
        this.updateScoreTxt();
    }
    // onBoom(): any {
    //     this.score--;
    //     if (this.score < 0) this.score = 0;
    //     this.updateProgress();
    //     this.updateScoreTxt();
    // }

    addScore(): any {
        this.score++;
        const old = this.score;
        if (old == this.MAX_SCORE) {
            this.score = 0;
        }
        this.updateScoreTxt();
        this.updateProgress();
        return old;
    }

    updateScoreTxt() {
        this.scoreTxt.text = `得分:${this.score}`;
    }

    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渲染
        this.egretRenderContainer = new egret.Sprite();
        this.addChild(this.egretRenderContainer);
        this._egretRender = new EgretRender(this.egretRenderContainer, this._engine);

        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 rect = new egret.Rectangle(0, 0, 380, 28);
        rect.width = 0;
        this.progressfront.mask = rect;

        const reslist = ['boom', 'gift', 'candy', 'coin', 'egg']
        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);
            }
        });

        [this['leftBtn'], this['rightBtn']].forEach(btn => {
            btn.addEventListener(egret.TouchEvent.TOUCH_TAP, (e: egret.TouchEvent) => {
                // createNewBubble(this,LabelType.candy)
                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);
        });

        createBtns(this);

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

        const color = 0x33CCFF;        /// 光晕的颜色，十六进制，不包含透明度
        const alpha = 0.4;             /// 光晕的颜色透明度，是对 color 参数的透明度设定。有效值为 0.0 到 1.0。例如，0.8 设置透明度值为 80%。
        const blurX = 35;              /// 水平模糊量。有效值为 0 到 255.0（浮点）
        const blurY = 35;              /// 垂直模糊量。有效值为 0 到 255.0（浮点）
        const strength = 2;            /// 压印的强度，值越大，压印的颜色越深，而且发光与背景之间的对比度也越强。有效值为 0 到 255。暂未实现
        const quality = egret.BitmapFilterQuality.HIGH;        /// 应用滤镜的次数，建议用 BitmapFilterQuality 类的常量来体现
        const inner = false;            /// 指定发光是否为内侧发光，暂未实现
        const knockout = false;            /// 指定对象是否具有挖空效果，暂未实现
        const glowFilter: egret.GlowFilter = new egret.GlowFilter(color, alpha, blurX, blurY,
            strength, quality, inner, knockout);
        this['scoreTxt'].filters = [glowFilter];

        this.updateScoreTxt();
        this.updateProgress();
    }

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

    progressfront: egret.DisplayObject;

    destroy() {
        super.destroy();
    }

}