import { DataManager } from "../libs/tw/manager/DataManager";
import AssetAdapter from "./AssetAdapter";
import PanelCtrl from "./ctrls/panelCtrl";
import SceneCtrl from "./ctrls/sceneCtrl";
import Loading from "./loading/Loading";
import ThemeAdapter from "./ThemeAdapter";
import { ModuleTypes } from "./types/sceneTypes";
import { getResPath } from "./utils";
import layers from "./views/layers";
import { PetIndexData } from "../libs/tw/data/pet/PetIndexData";
import { Buried } from '../libs/tw/util/Buried';
import TopLayerCtrl from './ctrls/topLayerCtrl';
import { initstatistics } from "./comm/statistics";
import { docEvent } from "./comm/DocumentEvent";
import { Panels, Scenes, Tops } from "./types/Scenes";
import Bar from "./components/Bar";

let MainStage:egret.Stage = null;
export { MainStage };

class Main extends eui.UILayer {
    protected createChildren(): void {
        super.createChildren();

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

        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());

        egret.ImageLoader.crossOrigin = "anonymous";

        DataManager.ins.petIndexData = new PetIndexData();
        DataManager.ins.petIndexData.update(window['CFG']);

        layers.init(this);
        Loading.init(layers.topLayer);
        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);
        TopLayerCtrl.instance.init(layers.topLayer);

        this.stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;
        // this.stage.scaleMode = egret.StageScaleMode.NO_BORDER;

        SceneCtrl.instance.registerScenes(Scenes);  // 注册Scene
        PanelCtrl.instance.registerPanels(Panels);  // 注册Panel
        TopLayerCtrl.instance.registerPanels(Tops); // 注册TopPanel

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

    private async runGame() {
        await this.loadResource();
        this.createGameScene();
    }

    private async loadResource() {
        try {
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await this.loadTheme();
        } 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);
        })
    }

    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        MainStage = this.stage;
        // DataManager.ins.customCfgData = window["CFG"];
        Buried.init();

        initstatistics();    // 页面停留时长（接口）
        docEvent(); // document事件（显示，隐藏，重载）

        // NetManager.ins.getRule((success, res)=>{
        //     if(!success){
        //         return;
        //     }
        //
        // });
        let bar = new Bar();
        this.addChild(bar);
        this.getGameRes().then(() => {
            SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
        });
    }

    //加载游戏中的资源
    private async getGameRes() {
        await RES.loadGroup('common');
        await RES.loadGroup('main_scene');
        // GDispatcher.dispatchEvent('progress', [100]);
    }
}

window['Main'] = Main;