import { Buried } from './../libs/tw/util/Buried';

import layers from "./views/layers";
import { getResPath } from "./utils";
import AssetAdapter from "./AssetAdapter";
import ThemeAdapter from "./ThemeAdapter";
import { DataManager } from "../libs/tw/manager/DataManager";
import Loading from "./loading/Loading";
import PanelCtrl from "./ctrls/panelCtrl";
import SceneCtrl from "./ctrls/sceneCtrl";
import { ModuleTypes } from './types/sceneTypes';
import MainScene from './mainScene/MainScene';
import { NetManager } from '../libs/tw/manager/NetManager';
import MsgPanel from './msgPanel/MsgPanel';
import GameScene from './gameScene/GameScene';
import PrizePanel from './prizePanel/PrizePanel';
import RulePanel from './rulePanel/RulePanel';

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

        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());

        egret.ImageLoader.crossOrigin = "anonymous";


        DataManager.ins.gameCfgData = window['CFG'];
        DataManager.ins.gameCfgData.gameInfo.gameId = window['gameId'];

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

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

        SceneCtrl.instance.registerSceneClass(ModuleTypes.MAIN_SCENE, MainScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.GAME_SCENE, GameScene);

        PanelCtrl.instance.registerPanelClass(ModuleTypes.MSG_PANEL, MsgPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL, PrizePanel);

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

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

    private resErrorListener(): void {
        //添加资源组加载失败事件
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceError, this);
        //添加资源加载失败事件
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onResourceError, this);
    }

    private onResourceError(): void {
        if (PanelCtrl.instance.isLoadedMsg) {
            this.showMsg('iknowBtn',
                [
                    { text: "网络竟然崩溃了～\n截图弹窗反馈给“捞小蜜”！" }//网络开小差了\n世界上最遥远的距离莫过于此
                ], () => {
                    SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE)
                }, () => {
                    SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE)
                });

        } else {
            alert('网络开小差了\n世界上最遥远的距离莫过于此');
            PanelCtrl.instance.removeAllPanel();
            SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE)
        }
    }

    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 textfield: egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        //获取游戏信息
        Loading.instace.show();
        NetManager.ins.getInfo((success: boolean) => {
            if (success) {
                Buried.init();
                SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
            } else {
                //提示用户，返回上一层，重新进入活动？？？？？
                this.showMsg('iknowBtn',
                    [
                        { text: "网络开小差了\n世界上最遥远的距离莫过于此" }
                    ], null, () => {
                        SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE)
                    });
            }

            Loading.instace.hide();
        });

    }

    //消息弹出框
    private showMsg(bname: string, msgArr: any, callBack?: Function, closeCallBack?: Function): void {
        var msgData: any = {
            btnName: bname,
            fontSize: 35,
            lineCount: 2,
            lineSpace: 15,
            callBack: callBack ? callBack.bind(this) : null,
            closeCallBack: closeCallBack ? closeCallBack.bind(this) : null,
            type: 'err'
        };
        msgData.msgArr = msgArr;

        PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData);
    }
}

window['Main'] = Main;