import getResPath from "../new_tc/getResPath";
import { check_webp_feature, getImgURL } from "../tc/util/GFun";
import { DataManager } from "../tw/manager/DataManager";
import { NetManager } from "../tw/manager/NetManager";
import { ABNetManager, GDispatcher, INetData } from "../tc/index";
import AssetAdapter from "./adapter/AssetAdapter";
import ThemeAdapter from "./adapter/ThemeAdapter";
import Alert from "./components/Alert";
import HTMLRulePanel from "./components/HTMLRulePanel";
import Loading from "./components/Loading";
import OptionsPanel from "./components/OptionsPanel";
import PlaySceneBase from "./components/PlaySceneBase";
import PrizePanel from "./components/PrizePanel";
import RankPanel from "./components/RankPanel";
import RulePanel from "./components/RulePanel";
import Tips from "./components/Tips";
import Box from "./components/Box";
import StartSceneBase from "./components/StartSceneBase";
import PanelCtrl from "./ctrls/panelCtrl";
import SceneCtrl from "./ctrls/sceneCtrl";
import showAlertPanel from "./ctrls/showAlertPanel";
import { ModuleTypes } from "./types/sceneTypes";
import layers from "./views/layers";
import { Buried } from "../tw/index";
import { urlReplace } from "../../src/Net";
import NoPrizePanel from "../../src/panels/NoPrizePanel";
import NoTimesPanel from "../../src/panels/NoTimesPanel";
import HasTimesPanel from "../../src/panels/HasTimesPanel";

export default class MainBase extends eui.UILayer {
    constructor() {
        super();
        check_webp_feature();
        Loading.instace.loadImage();
        // DataManager.ins.gameCfgData = window['CFG'];
        // DataManager.ins.gameCfgData.gameInfo.gameId = window["gameId"];
        this.getData();
    }

    protected registerModules() {
        const panels = [
            // [ModuleTypes.ALERT_PANEL, { cls: Alert }],
            // [ModuleTypes.TIPS_PANEL, { cls: Tips }],
            // [ModuleTypes.BOX_PANEL, { cls: Box }],
            [ModuleTypes.RULE_PANEL, { cls: RulePanel }],
            // [ModuleTypes.HTML_RULE_PANEL, { cls: HTMLRulePanel }],
            // [ModuleTypes.OPTIONS_PANEL, { cls: OptionsPanel }],
            [ModuleTypes.PRIZE_PANEL, { cls: PrizePanel }],
            // [ModuleTypes.RANK_PANEL, { cls: RankPanel }],

            [ModuleTypes.NOPRIZE_PANEL, { cls: NoPrizePanel }],
            [ModuleTypes.NOTIMES_PANEL, { cls: NoTimesPanel }],
            [ModuleTypes.HASTIMES_PANEL, { cls: HasTimesPanel }],
        ];

        const scenes = [
            // [ModuleTypes.START_SCENE, this.startSceneConfig],
            [ModuleTypes.PLAY_SCENE, this.playSceneConfig]
        ];

        panels.forEach(item => PanelCtrl.instance.registerPanel(item[0], item[1]));
        scenes.forEach(item => SceneCtrl.instance.registerScene(item[0], item[1]));

        GDispatcher.addEvent(ABNetManager.ERROR, (net: INetData, msg = '', result) => {
            const msgData = {
                net: net,
                msg: msg,
            };



            // console.log(result)
            // console.log(DataManager.ins.doJoinData)
            // var msg = msgData ? (msgData.msg? msgData.msg : '啊哦~\n网络异常') : '啊哦~\n网络异常';
            // console.log(msgData)

            // if(localStorage.gameState=="gameSubmit"){
            //     this.doloseGameBuried()
            //     msg="啊哦~\n您和奖品擦肩而过"
            //     let panel = showAlertPanel(msg);
            //     panel.addEventListener('onDestroy', () => {
            //         NetManager.ins.clickLog(this.exposure["loseGame"]);
            // }, this)
            // }else if(localStorage.gameState=="getSubmitResult"){
            //     this.doBuried()
            //     msg="啊哦~网络异常\n请到[我的奖品]查看是否中奖吧"
            //     let panel = showAlertPanel(msg);
            //     panel.addEventListener('onDestroy', () => {
            //         NetManager.ins.clickLog(this.exposure["getSubmitResult"]);
            // }, this)
            // }else if(localStorage.gameState2!="getStartOrderStatus"){
            //    // alert(localStorage.gameState2)

            //    if(msg.indexOf("积分不足")!=-1){
            //       msg="积分不够啦!\n多攒些积分再来吧～"
            //    }

            //     let panel = showAlertPanel(msg);
            //         panel.addEventListener('onDestroy', () => {}, this)
            // }

        }, this);
    }

    exposure = []

    protected get startSceneConfig() {
        return { cls: StartSceneBase }
    }
    protected get playSceneConfig() {
        return { cls: PlaySceneBase }
    }

    protected getData() {
        // NetManager.ins.getInfo();
    }

    protected createChildren(): void {
        super.createChildren();
        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            // egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            // egret.ticker.resume();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        const assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());

        egret.ImageLoader.crossOrigin = "anonymous";

        //替换projectId
        urlReplace();

        layers.init(this);
        Loading.init(layers.topLayer);
        Loading.instace.show();

        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);

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

        this.registerModules();

        // this.loadFirstScreen();
        Loading.instace.show();

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

    loadAtlas() {
        // if (!window['development']) {
        //     loadSpriteSheet().then((spritesheet: egret.SpriteSheet) => {
        //         Loading.instace.setSpriteSheet(spritesheet);
        //         const t = Date.now() - window['__startTime__'];
        //         console.log(`首屏loading显示时间：${t}ms`);
        //     })
        // }
    }

    // _firstBgLoaded = false;
    // loadFirstScreen() {
    //     this.loadFirstBG((bitmap: egret.Bitmap) => {
    //         const t = Date.now() - window['__startTime__'];
    //         console.log(`首屏背景显示时间：${t}ms`);
    //         layers.addFirstBackground(bitmap);
    //         this._firstBgLoaded = true;
    //         this.check();
    //     });
    // }

    // loadFirstBG(callback) {
    //     const onImageLoaded = (e: egret.Event) => {
    //         const imageLoader: egret.ImageLoader = e.currentTarget;
    //         const bitmapData: egret.BitmapData = imageLoader.data;
    //         const texture = new egret.Texture();
    //         texture._setBitmapData(bitmapData);
    //         const bitmap = new egret.Bitmap(texture);
    //         callback(bitmap);
    //     }
    //     const imageLoader = new egret.ImageLoader();
    //     imageLoader.once(egret.Event.COMPLETE, onImageLoaded, this);
    //     const url = getResPath() + "resource/assets/startScene/startscenebg.jpg";
    //     // url = getImgURL(url);
    //     imageLoader.load(url);
    // }

    private async runGame() {
        await this.loadResource()
        if (!window['development']) {
            RES.getResAsync(`common_json`);
        } else {

        }
        // NetManager.ins.getInfo(()=>{
        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.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            const theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    /**
     * 创建场景界面
     * Create scene interface
     */
    _startSceneReady = false;
    protected createGameScene() {
        // SceneCtrl.instance.change(ModuleTypes.START_SCENE, null, () => {
        //     this._startSceneReady = true;
        //     this.check();
        // });
        SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE, null, () => {
            this._startSceneReady = true;
            this.check();
        });
    }

    check() {
        if (this._startSceneReady) {
            // layers.removeFirstBackground();
            const t = Date.now() - window['__startTime__'];
            console.log(`start scene显示时间：${t}ms`);
            //开始场景图集和开始场景背景全部加载完成并显示
        }

    }
}