import AssetAdapter from "./AssetAdapter";
import ThemeAdapter from "./ThemeAdapter";
import { getResPath } from "./utils";

class Main extends eui.UILayer {
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        alert(1);
        let img: egret.Bitmap = new egret.Bitmap();
        img = this.createBitmapByName("bg_jpg");
        img.width = this.stage.stageWidth;
        img.height = this.stage.stageHeight;
        this.addChild(img);
        this.CreateWorld();
        this.CreatePlane();

        this.addEventListener(egret.Event.ENTER_FRAME, this.update, this);
        this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onButtonClick, this);
    }

    //使用P2物理引擎创建物理应用的过程大致分为5个步骤：
    // 1创建world世界
    // 2创建shape形状
    // 3创建body刚体
    // 4实时调用step()函数，更新物理模拟计算
    // 5基于形状、刚体，使用Egret渲染，显示物理模拟效果

    //创建Word世界
    private world: p2.World;
    private CreateWorld() {
        this.world = new p2.World();
        //设置world为睡眠状态
        this.world.sleepMode = p2.World.BODY_SLEEPING;
        // gravity=[x,y] x为水平方向重力，正数表示方向向右。y为垂直方向重力，正数表示方向向下。
        this.world.gravity = [0, 10];
        // this.world.gravity = [0, 10];
    }

    //生成地板Plane
    private planeBody: p2.Body;
    private CreatePlane() {
        let planeShape: p2.Plane = new p2.Plane();
        this.planeBody = new p2.Body({
            type: p2.Body.STATIC,   //刚体类型
            position: [0, this.stage.stageHeight],  //刚体的位置
        });
        this.planeBody.angle = Math.PI;//Plane相当于地面，默认面向Y轴方向。将地面翻转180度
        this.planeBody.displays = [];
        this.planeBody.addShape(planeShape);
        this.world.addBody(this.planeBody);
    }

    private shpeBody: p2.Body;
    //贴图显示对象
    private display: egret.DisplayObject;
    private onButtonClick(e: egret.TouchEvent) {
        if (Math.random() > 0.5) {
            //添加方形刚体 
            var boxShape = new p2.Box({ width: 140, height: 80 });
            this.shpeBody = new p2.Body({
                mass: 1,
                position: [e.stageX, e.stageY],
                angularVelocity: 1//下落时旋转的速度
            });
            this.shpeBody.addShape(boxShape);
            this.world.addBody(this.shpeBody);
            this.display = this.createBitmapByName("rect_png");
            this.display.width = boxShape.width;
            this.display.height = boxShape.height;
            console.log(e.stageX, e.stageY);

        }
        else {
            //添加圆形刚体
            var circleShape = new p2.Circle({ radius: 60 });
            this.shpeBody = new p2.Body({ mass: 1, position: [e.stageX, e.stageY] });
            this.shpeBody.addShape(circleShape);
            this.world.addBody(this.shpeBody);
            this.display = this.createBitmapByName("circle_png");
            this.display.width = circleShape.radius * 2
            this.display.height = circleShape.radius * 2
        }
        //Egret中加载进来的图像，其原点默认为左上角，而P2中刚体的原点处于其中心位置，如下图（盗了一张图）
        this.display.anchorOffsetX = this.display.width / 2
        this.display.anchorOffsetY = this.display.height / 2;
        this.display.x = -100;
        this.display.y = -100;
        this.display.rotation = 270
        this.shpeBody.displays = [this.display];
        this.addChild(this.display);
    }

    //帧事件，步函数
    private update() {
        this.world.step(1);
        var l = this.world.bodies.length;
        for (var i: number = 0; i < l; i++) {
            var boxBody: p2.Body = this.world.bodies[i];
            var box: egret.DisplayObject = boxBody.displays[0];
            if (box) {
                box.x = boxBody.position[0];
                box.y = boxBody.position[1];
                //这里刷新图片旋转
                box.rotation = boxBody.angle * 180 / Math.PI;
                if (boxBody.sleepState == p2.Body.SLEEPING) {
                    box.alpha = 0.5;
                }
                else {
                    box.alpha = 1;
                }
            }
        }
    }

    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     */
    private createBitmapByName(name: string): egret.Bitmap {
        var result: egret.Bitmap = new egret.Bitmap();
        var texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;

    }

    protected createChildren(): void {
        super.createChildren();

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());


        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        const result = await RES.getResAsync("description_json")
        await platform.login();
        const userInfo = await platform.getUserInfo();
        console.log(userInfo);

    }

    private async loadResource() {
        try {
            // const loadingView = new LoadingUI();
            // this.stage.addChild(loadingView);
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await this.loadTheme();
            await RES.loadGroup("preload", 0);
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }
}

window['Main'] = Main;