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

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.updateBrickBody();

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

    updateBrickBody(): void {
        for (var i = 0; i < 1; i++) {
            var brick = new Brick();
            var x = this.stage.stageWidth >> 1;
            var y = 1000;
            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);
        }
    }

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

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

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