import PanelCtrl from "../../src/ctrls/panelCtrl";
import SceneCtrl from "../../src/ctrls/sceneCtrl";
import Loading from "../../src/loading/Loading";
import { getResPath } from "../../src/utils";
import layers from "../../src/views/layers";
import { DataManager } from "../tw/manager/DataManager";
import { NetManager } from "../tw/manager/NetManager";
import AssetAdapter from "./adapter/AssetAdapter";
import ThemeAdapter from "./adapter/ThemeAdapter";
import { check_webp_feature } from "../tc/util/GFun";

export default class MainBase extends eui.UILayer {
    constructor() {
        super();
        check_webp_feature();
    }

    private injectRES() {
        if (RES.fileSystem['getFileOld']) return;
        RES.fileSystem['getFileOld'] = RES.fileSystem.getFile;
        window['RES'].fileSystem.getFile = function (filename: string) {
            //生效情况
            //RES.getResByUrl spritesheet类型
            //不生效
            //RES.getResAsync('net_png')  spritesheet类型
            if (filename.indexOf('.json') != -1) {
                var arr = filename.split('.json')[0].split('/');
                var filename1 = arr[arr.length - 1] + '_png';
                var filename2 = filename.split('.json')[0] + '.png';
                if (!RES.fileSystem['fsData'][filename1])
                    RES.fileSystem['fsData'][filename1] =
                        { name: filename1, type: 'image', url: filename2, root: '', extra: '1' };
            }

            var result = RES.fileSystem['getFileOld'](filename);
            if (result && result.url && check_webp_feature()) {
                //生效情况
                //RES.getResByUrl jpg or png类型
                //RES.getResAsync('monkey_png')
                if (filename.indexOf('png') != -1 || filename.indexOf('jpg') != -1)
                    result = JSON.parse(JSON.stringify(result));
                // result.url = result.url.replace('.png', '.png?x-oss-process=image/format,webp');
                result.url = result.url.replace('.jpg', '.jpg?x-oss-process=image/format,webp');
            }
            return result;
        }
    }
    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
        //注入自定义的素材解析器
        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);

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

        this.registerModules();

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

    protected getData() {

    }

    protected registerModules() { }

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

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