import AssetAdapter from "./AssetAdapter";
import MPanelCtrl from "./MainSrc/MCtrls/MPanelCtrl";
import MSceneCtrl from "./MainSrc/MCtrls/MSceneCtrl";
import Loading from "./loading/Loading";
import layers from "./MainSrc/MViews/MLayers";
import MTopLayerCtrl from './MainSrc/MCtrls/MTopLayerCtrl';
import { getResPath, calculateReward, isWeiXin, shareActivity } from "./MainSrc/Global/GUtils";
import { customClassPrototype } from "./MainSrc/MComponents/Custom";
import { Decorator } from "./MainSrc/Decorator/Decorator";
import ToastPanel from "./MainSrc/MComponents/MToastPanel";
import MProgressBar from "./MainSrc/MUI/MProgressBar";
import MButton from "./MainSrc/MUI/MButton";
import Net from "./MainSrc/Global/Net";
import StartScene from "./MainSrc/Scene/StartScene";
import MTimer from "./MainSrc/MComponents/MTimer";
import MTweenMgr from "./MainSrc/MComponents/MTween";
import PhycicsSystem from "./MainSrc/Game/PhycicsSystem";
import { NetUtils } from "./MainSrc/Global/NetUtils";
import MLabel from "./MainSrc/MUI/MLabel";
import { MConfigs } from "./MainSrc/Global/MConfigs";
import MainScene from "./MainSrc/Scene/MainScene";
import SceneCtrl from "./ctrls/sceneCtrl";
import MBuried from "./MainSrc/Global/MBuried";
import ThemeAdapter from "./ThemeAdapter";
import MTextEditor from "./MainSrc/MUI/MTextEditor";

@Decorator.OnUpdate
class Main extends eui.UILayer {
    constructor() {
        super();
        customClassPrototype();
    }

    protected createChildren() {
        super.createChildren();
        this.init();
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
        egret.ImageLoader.crossOrigin = "anonymous";
        //设置屏幕适配方式
        this.stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;

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

    private getShareInfo() {
        return new Promise(resolve => {
            Net.sendGet(Net.Url.GetShareInfo, {
                wxdebug: false,
                url: location.href
            }, (res) => {
                let wx = window["wx"];
                wx.config({
                    debug: false,
                    appId: res.wxappid,
                    timestamp: res.wxtimestamp,
                    nonceStr: res.wxnonceStr,
                    signature: res.wxsignature,
                    jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage']
                });

                wx.error(function (res: any) {
                    console.error(res);
                    // resolve();
                });

                wx.ready(function () {
                    resolve();
                });
            });
        });
    }

    private init() {
        MTimer.init();
        MTweenMgr.instance.init();
        // PhycicsSystem.init();
        //替换URL
        Net.urlReplace();
        //从皮肤的mconfig对象上更新MConfig
        MConfigs.updateConfig();
        MBuried.init(MConfigs.appId, NetUtils.getProjectId());

        Net.defaultOnFail = () => {
            MSceneCtrl.instance.change(StartScene);
            MPanelCtrl.instance.closeAll();
            Loading.instace.hide();
        }

        layers.init(this);
        Loading.init(layers.topLayer);
        MPanelCtrl.instance.init(layers.popupLayer);
        MSceneCtrl.instance.init(layers.sceneLayer);
        MTopLayerCtrl.instance.init(layers.topLayer);
        ToastPanel.parent = layers.toastLayer;
    }

    private async runGame() {
        await this.loadResource()
        if (isWeiXin()) {
            await this.getShareInfo();
            shareActivity();
        }

        this.createGameScene();
        /* setTimeout(() => {
        }, 3000); */
    }

    /* private loadExml(url: string) {
        return new Promise<any>((resolve) => {
            EXML.load(url, (clazz: any) => {
                resolve(clazz)
            }, this);
        });
    } */

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

    private loadTheme() {
        return new Promise((resolve, reject) => {
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, (e: any) => {
                resolve();
            }, this);

        })
    }

    /**
     * 创建场景界面
     * Create scene interface
     */
    protected async createGameScene() {
        let res = await NetUtils.getUserInfo();
        if (res.data == null) {
            MSceneCtrl.instance.change(StartScene);
        } else {
            MSceneCtrl.instance.change(MainScene, {
                response: res
            });
        }
    }
}

window["Main"] = Main;
window["MProgressBar"] = MProgressBar;
window["MButton"] = MButton;
window["MLabel"] = MLabel;
window["MTextEditor"] = MTextEditor;