import { DataManager } from "../libs/tw/manager/DataManager";
import { NetManager } from "../libs/tw/manager/NetManager";
import AssetAdapter from "./AssetAdapter";
import PanelCtrl from "./MVC/ctrls/panelCtrl";
import SceneCtrl from "./MVC/ctrls/sceneCtrl";
import Loading from "./Common/loading/Loading";
import ThemeAdapter from "./ThemeAdapter";
import { ModuleTypes } from "./types/sceneTypes";
import { getResPath } from "./utils";
import layers from "./MVC/views/layers";
import { PetIndexData } from "../libs/tw/data/pet/PetIndexData";
import { Buried } from '../libs/tw/util/Buried';
import LoadingScene from './Common/loadingScene/loadingScene';
import { GDispatcher } from '../libs/tc/util/GDispatcher';
import TopLayerCtrl from './MVC/ctrls/topLayerCtrl';
import ToastPanel from './Common/toastPanel/ToastPanel';
import { ABNetManager } from '../libs/tc/manager/ABNetManager';

//////

import CreditsTipPanel from './Panels/CreditsTipPanel/CreditsTipPanel';
import NoMorePanel from "./Panels/NoMorePanel/NoMorePanel";
import NoPrizePanel from "./Panels/NoPrizePanel/NoPrizePanel";
import PrizePanel from "./Panels/PrizePanel/PrizePanel";
import StartScene from "./Scene/startScene/StartScene";
import RulePanel from "./Panels/RulePanel/RulePanel";
import MyPrizeScene from "./Scene/MyPrizeScene/MyPrizeScene";

//////

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

        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']);
        // NetManager.ins.getCredits(()=>{});

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

        Buried.init();

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

        SceneCtrl.instance.registerSceneClass(ModuleTypes.LOADING_SCENE, LoadingScene);

        ///////
        SceneCtrl.instance.registerSceneClass(ModuleTypes.START_SCENE, StartScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.MYPRIZE_SCENE, MyPrizeScene);

        PanelCtrl.instance.registerPanelClass(ModuleTypes.CREDITS_TIP_PANEL, CreditsTipPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.NO_MORE_PANEL, NoMorePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.NO_PRIZE_PANEL, NoPrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        

        //////

        TopLayerCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, ToastPanel);

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

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        // RES.loadGroup("msg", 10);
    }

    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("msg", 10);
            // this.stage.removeChild(loadingView);
        }
        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);

        })
    }

    private onError(net: any, desc: any, result): void {
        console.log(desc);
        console.log(result);
        var msg: string;
        var msgArr: any = window['errorMessage'];
        if (!isNaN(desc)) {
            msg = msgArr[desc] ? msgArr[desc] : '活动太火爆了，请稍后再来～';
        } else {
            msg = desc;
        }

        var code;
        if (result) {
            code = result.code;
        }
        if (code == "600001" || code == "100002") {
            this.showToast("昵称不符合，请重新输入");
        } else if (code == "0800101") {
            this.showToast("网络异常");
        } else {
            if (msg) {
                this.showToast(msg);
            } else {
                this.showToast("网络异常，请检查网络稍后重试");
            }
        }
    }

    showToast(val) {
        //console.log(val)
        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: val });
    }

    private textfield: egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        Buried.init();
        //获取签到信息
        // DataManager.ins.customCfgData = window["CFG"]
        // NetManager.ins.ajaxElement((success) => {
        //     if (!success) { return; }
        //     GDispatcher.addEvent(ABNetManager.ERROR, this.onError, this);
        //     this.getGameRes();
        // })
        this.getGameRes();
    }

    //加载游戏中的资源
    private async getGameRes() {
        // await RES.loadGroup('loading_scene');
        SceneCtrl.instance.change(ModuleTypes.LOADING_SCENE);

        GDispatcher.dispatchEvent('progress', [10]);
        await RES.loadGroup('common');

        await RES.loadGroup('loading');
        await RES.loadGroup('loading_scene');
        GDispatcher.dispatchEvent('progress', [20]);
        await RES.loadGroup('start_scene');

        GDispatcher.dispatchEvent('progress', [35]);
        await RES.loadGroup('creditsTip_panel');

        GDispatcher.dispatchEvent('progress', [50]);
        await RES.loadGroup('noMore_panel');

        GDispatcher.dispatchEvent('progress', [65]);
        await RES.loadGroup('noPrize_panel');

        GDispatcher.dispatchEvent('progress', [80]);
        await RES.loadGroup('noTimes_panel');

        GDispatcher.dispatchEvent('progress', [90]);
        await RES.loadGroup('prize_panel');
        
        GDispatcher.dispatchEvent('progress', [100]);
    }
}

window['Main'] = Main;