import { INetData } from '../tc/interface/INetData';
import { ABNetManager } from '../tc/manager/ABNetManager';
import { GDispatcher } from '../../libs/tc/util/GDispatcher';
import { ModuleTypes } from './../../src/types/sceneTypes';
import PanelCtrl from "../../src/ctrls/panelCtrl";
import SceneCtrl from "../../src/ctrls/sceneCtrl";
import Waiting from "../../src/waiting/Waiting";
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";
import MovieClipCtrl from "../../src/ctrls/MovieClipCtrl";
import ToastCtrl from '../../src/ctrls/toastCtrl';

export default class MainBase extends eui.UILayer {
    constructor() {
        super();
        check_webp_feature();
        this.initStateText();
        Waiting.instance.loadImage();
        this.GDispatchEvent();
    }

    // 设置派发事件
    protected GDispatchEvent() {
        GDispatcher.addEvent(ABNetManager.ERROR, (net: INetData, msg = '') => {
            const msgData = {
                net: net,
                msg: msg,
                // sureBtnTxt: TlLang.lang_011
            };
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData)
        }, this);
        // 监听当预加载资源加载完毕
        GDispatcher.addEvent('PreloadLoaded', () => {
            // this.createGameScene()
            Waiting.instance.show()
        }, this);
        GDispatcher.addEvent('NormalLoaded', () => {
            Waiting.instance.hide();
            this.createGameScene()
        }, this);
    }

    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 loadBg(name, 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);
            if (callback) {
                callback(bitmap);
            }
        }
        const imageLoader = new egret.ImageLoader();
        imageLoader.once(egret.Event.COMPLETE, onImageLoaded, this);
        const url = getResPath() + `resource/assets/${name}`;
        // url = getImgURL(url);
        imageLoader.load(url);
    }

    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.customCfgData = window['CFG'];
        // DataManager.ins.gameCfgData = window['CFG'];
        // DataManager.ins.gameCfgData.gameInfo.gameId = window["gameId"];

        setTimeout(() => {
            console.log('stageHeight', this.stage.stageHeight);
            console.log('height', this.stage.height);
        }, 2000);

        // 层级初始化
        layers.init(this);
        Waiting.init(layers.topLayer);
        ToastCtrl.instance.init(layers.toastLayer);
        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);

        // 固定宽
        this.stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;
        this.registerModules();

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

    protected getData() { }

    protected registerModules() { }

    private async runGame() {
        await this.loadResource();
        await MovieClipCtrl.instance.init();
    }

    private async loadResource() {
        try {
            RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
            console.log("开始加载配置文件");
            console.log('getResPath()', getResPath());
            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);

        })
    }

    /**
     * 配置文件加载完成,开始预加载Preload资源组。
     */
    private onConfigComplete(event: RES.ResourceEvent): void {
        this.trace("配置文件加载成功");
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        //添加资源组加载完成事件
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        //添加资源组加载失败事件
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        //添加资源加载失败事件
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onResourceItemLoadError, this);
        //添加资源组加载进度事件
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        //开始加载 preload 资源组
        this.trace("开始加载Preload组");
        RES.loadGroup("Preload");
    }

    /**
     * preload资源组加载完成
     */
    protected onResourceLoadComplete(event: RES.ResourceEvent): void {
        if (event.groupName == "Preload") {
            this.trace("preload组加载完成");
            this.trace("开始加载Normal资源");
            GDispatcher.dispatchEvent('PreloadLoaded');
            RES.loadGroup("Normal");
        } else if (event.groupName == "Normal") {
            this.trace("Normal组加载完成");
            this.trace("开始加载Delay资源");
            GDispatcher.dispatchEvent('NormalLoaded');
            RES.loadGroup("BigImage");
        } else if (event.groupName == 'BigImage') {
            this.trace("BigImage组加载完成");
            GDispatcher.dispatchEvent('BigImageLoaded');
            RES.loadGroup("Delay");
        } else if (event.groupName == 'Delay') {
            this.trace("Delay组加载完成");
            GDispatcher.dispatchEvent('DelayLoaded');
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        }
    }

    /**
     * preload资源组加载进度
     */
    protected onResourceProgress(event: RES.ResourceEvent): void {
        // if (event.groupName == "Preload") {
        //     this.trace(`${event.groupName}资源加载进度 : ${event.itemsLoaded} / ${event.itemsTotal}`);
        // } else if (event.groupName == "Normal") {
        //     this.trace(`${event.groupName}资源加载进度 : ${event.itemsLoaded} / ${event.itemsTotal}`);
        // } else if (event.groupName == "Delay") {
        //     this.trace(`${event.groupName}资源加载进度 : ${event.itemsLoaded} / ${event.itemsTotal}`);
        // } else if (event.groupName == "BigImage") {

        // }
        // this.trace(`${event.groupName}资源加载进度 : ${event.itemsLoaded} / ${event.itemsTotal}`);
    }

    /**
     * 资源组加载出错
     */
    protected onResourceLoadError(event: RES.ResourceEvent): void {
        this.trace(`${event.groupName}组资源加载失败`);
        //忽略加载失败的项目
        this.onResourceLoadComplete(event);
    }

    /**
     * 资源加载出错
     */
    protected onResourceItemLoadError(event: RES.ResourceEvent): void {
        this.trace("项目加载失败,url : " + event.resItem.url);
    }

    private stateText: egret.TextField;
    private text: string = "";

    private initStateText(): void {
        this.stateText = new egret.TextField();
        this.stateText.size = 22;
        this.stateText.text = this.text;
        this.stateText.width = 480;
        this.addChild(this.stateText);
    }

    protected trace(msg: any): void {
        // this.text = this.text + "\n" + msg;
        // this.stateText.text = this.text;
        egret.log(msg);
    }

    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene() {
        // GDispatcher.removeEvent('NormalLoaded',this.createGameScene,this);
        console.log('创建开始场景')

    }
}