import { getResPath } from "./utils";
import Gun from "./Gun";
import World from "./World";
import Brick from "./Brick";
import { FACTOR } from "./consts";
import Wall from "./Wall";

export class Main extends eui.UILayer {
    private _gun: Gun;
    private _world: World;
    protected createGameScene(): void {
        this._world = new World();
        this._gun = new Gun(this, this._world);
        this._world.gun = this._gun;
        this._world.skin = new egret.Sprite();

        this.addChild(this._world.skin);
        this.addChild(this._gun);

        this._gun.x = this.stage.stageWidth >> 1;
        this._gun.y = 100;
        this._gun.enable();

        this.createGround();

        this.addBricks();

        //添加游戏帧频事件
        this.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
        this._gun.addEventListener('fire', this.onFire, this);
    }

    ballCounter = 0;
    onFire() {
        this.ballCounter++;
        if (this.ballCounter >= 2) {
            this.ballCounter = 0;
            this.currentY += 130;
            this.addBricks();
            this._world.bodies.forEach(body => {
                if (body instanceof Brick) {
                    body.position[1] -= 50;
                }
            })
        }
    }

    createGround() {
        const left = new Wall(true);
        const right = new Wall(false);
        this._world.addBody(left);
        this._world.addBody(right);
        this._world.skin.addChild(left.skin);
        this._world.skin.addChild(right.skin);
        left.position = [left.skin.width / 2, left.skin.height / 2];
        right.position = [this.stage.stageWidth - right.skin.width / 2, right.skin.height / 2];
        this._world.addBody(left);
        this._world.addBody(right);
        right.updateSkin();
        left.updateSkin();
    }

    currentY: number = 700;
    addBricks(): void {
        const xlist = [150, 300, 450, 600];
        for (var i = 0; i < xlist.length; i++) {
            var brick = new Brick(Math.ceil(Math.random() * 1) + 1);
            var x = xlist[i];
            var y = Math.random() * 50 + this.currentY;
            brick.position = [x / FACTOR, y / FACTOR];
            brick.updateSkin();
            brick.angle = (-Math.random() * Math.PI / 4) + (Math.random() * Math.PI / 4);
            this._world.skin.addChild(brick.skin);
            this._world.addBody(brick);
            brick.onceDestroy(this.onBrickDestroy, this)
        }
    }

    onBrickDestroy(e: egret.Event) {
        const brick = e.data as Brick;
        this._world.removeBody(brick);
        this._world.skin.removeChild(brick.skin);
    }

    protected createChildren(): void {
        super.createChildren();
        this.runGame().catch(e => {
            console.log(e);
        })
    }

    loop() {
        this._world.step(1 / 60);
        this._world.loop();
    }

    private async runGame() {
        window['_error_storage_'] = [];
        window['ERROR_CONFIG'] = {
            client: "duiba-game",
            pageId: 'fis',
            imgUrl: "http://retcode.tuipink.com/report?"
        };

        function r() {
            window['_error_storage_'] && window['_error_storage_'].push([].slice.call(arguments))
        }

        window.addEventListener && window.addEventListener("error", r, true);

        var t = 3,
            n = function e() {
                var r = document.createElement("script");
                r.async = !0, r.src = "//yun.tuia.cn/tuia/skyeye/skyeye.js", r.crossOrigin = "anonymous", r.onerror =
                    function () {
                        t-- , t > 0 && setTimeout(e, 1500)
                    }, document.head && document.head.appendChild(r)
            };
        setTimeout(n, 1500);


        await this.loadResource()
        this.createGameScene();
    }

    private async loadResource() {
        try {
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await RES.loadGroup("preload", 0);
        }
        catch (e) {
            console.error(e);
        }
    }
}

window['Main'] = Main;