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

export class Main extends eui.UILayer {
    private _gun: Gun;
    private _world: World;
    protected createGameScene(): void {
        this._world = new World(this);
        this._gun = new Gun(this, this._world);
        this.addChild(this._gun);
        this._gun.x = this.stage.stageWidth >> 1;
        this._gun.y = 100;
        this._gun.enable();

        setInterval(() => {
            this._gun.fire();
        }, 500);

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

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

    loop() {
        this._world.step(1);
        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;