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";
import {NetManager} from "../libs/tw/manager/NetManager";
import {Tools} from "./Tools";
import {showToast} from "./comm/UtilsConst";

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.loadingLayer);
        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();
        await 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<void>((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 async createGameScene() {
        MainStage = this.stage;

        Buried.init();

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

        // NetManager.ins.getRule((success, res) => {
        // });

        if (window['bar']) {
            this.addChild(new Bar()).y = -2;
        }

        await this.getGameRes();

        const consumerInfo = await Tools.getConsumerInfo();
        if (!consumerInfo) {
            showToast('获取用户信息失败');
            return;
        }

        await Tools.getQuestionList();  // 问题列表
        await Tools.getMedalData();  // 勋章数据
        await Tools.gameGroupPrize();  // 游戏合集发奖
        // await Tools.gameFrontVariable();//
        await Tools.gameFrontInfo();
        await Tools.gameCustomInfo();

        const areaPrice = await Tools.getAreaPrice();
        if (!areaPrice) {
            showToast('获取土地价格失败');
            return;
        }

        let queryParams: any = {};

        let search = window.location.search;
        try {
            search = top.location.search;  //尝试获取顶层的链接
        } catch (e) {
        }

        for (let item of search.replace('?', '').split('&')) {
            let arr = item.split('=');
            queryParams[arr[0]] = arr.length === 1 ? true : arr[1];
        }

        // goHome
        if (queryParams.gohome) {
            SceneCtrl.instance.change(ModuleTypes.ROOM_SCENE);
        } else {
            SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
        }

    }

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

window['Main'] = Main;
