"use strict";
var __reflect = (this && this.__reflect) || function (p, c, t) {
    p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
};
var __extends = this && this.__extends || function __extends(t, e) { 
 function r() { 
 this.constructor = t;
}
for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]);
r.prototype = e.prototype, t.prototype = new r();
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var ABNetManager_1 = require("../tc/manager/ABNetManager");
var GDispatcher_1 = require("../../libs/tc/util/GDispatcher");
var sceneTypes_1 = require("./../../src/types/sceneTypes");
var panelCtrl_1 = require("../../src/ctrls/panelCtrl");
var sceneCtrl_1 = require("../../src/ctrls/sceneCtrl");
var Waiting_1 = require("../../src/waiting/Waiting");
var utils_1 = require("../../src/utils");
var layers_1 = require("../../src/views/layers");
var DataManager_1 = require("../tw/manager/DataManager");
var AssetAdapter_1 = require("./adapter/AssetAdapter");
var ThemeAdapter_1 = require("./adapter/ThemeAdapter");
var GFun_1 = require("../tc/util/GFun");
var MovieClipCtrl_1 = require("../../src/ctrls/MovieClipCtrl");
var toastCtrl_1 = require("../../src/ctrls/toastCtrl");
var MainBase = (function (_super) {
    __extends(MainBase, _super);
    function MainBase() {
        var _this = _super.call(this) || this;
        _this.text = "";
        GFun_1.check_webp_feature();
        _this.initStateText();
        Waiting_1.default.instance.loadImage();
        _this.GDispatchEvent();
        return _this;
    }
    // 设置派发事件
    MainBase.prototype.GDispatchEvent = function () {
        var _this = this;
        GDispatcher_1.GDispatcher.addEvent(ABNetManager_1.ABNetManager.ERROR, function (net, msg) {
            if (msg === void 0) { msg = ''; }
            var msgData = {
                net: net,
                msg: msg,
            };
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.MSG_PANEL, msgData);
        }, this);
        // 监听当预加载资源加载完毕
        GDispatcher_1.GDispatcher.addEvent('PreloadLoaded', function () {
            // this.createGameScene()
            Waiting_1.default.instance.show();
        }, this);
        GDispatcher_1.GDispatcher.addEvent('NormalLoaded', function () {
            Waiting_1.default.instance.hide();
            _this.createGameScene();
        }, this);
    };
    MainBase.prototype.injectRES = function () {
        if (RES.fileSystem['getFileOld'])
            return;
        RES.fileSystem['getFileOld'] = RES.fileSystem.getFile;
        window['RES'].fileSystem.getFile = function (filename) {
            //生效情况
            //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 && GFun_1.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;
        };
    };
    MainBase.prototype.loadBg = function (name, callback) {
        var onImageLoaded = function (e) {
            var imageLoader = e.currentTarget;
            var bitmapData = imageLoader.data;
            var texture = new egret.Texture();
            texture._setBitmapData(bitmapData);
            var bitmap = new egret.Bitmap(texture);
            if (callback) {
                callback(bitmap);
            }
        };
        var imageLoader = new egret.ImageLoader();
        imageLoader.once(egret.Event.COMPLETE, onImageLoaded, this);
        var url = utils_1.getResPath() + ("resource/assets/" + name);
        // url = getImgURL(url);
        imageLoader.load(url);
    };
    MainBase.prototype.createChildren = function () {
        var _this = this;
        _super.prototype.createChildren.call(this);
        egret.lifecycle.addLifecycleListener(function (context) {
            // custom lifecycle plugin
        });
        egret.lifecycle.onPause = function () {
            // egret.ticker.pause();
        };
        egret.lifecycle.onResume = function () {
            // egret.ticker.resume();
        };
        //inject the custom material parser
        //注入自定义的素材解析器
        var assetAdapter = new AssetAdapter_1.default();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter_1.default());
        egret.ImageLoader.crossOrigin = "anonymous";
        DataManager_1.DataManager.ins.customCfgData = window['CFG'];
        // DataManager.ins.gameCfgData = window['CFG'];
        // DataManager.ins.gameCfgData.gameInfo.gameId = window["gameId"];
        setTimeout(function () {
            console.log('stageHeight', _this.stage.stageHeight);
            console.log('height', _this.stage.height);
        }, 2000);
        // 层级初始化
        layers_1.default.init(this);
        Waiting_1.default.init(layers_1.default.topLayer);
        toastCtrl_1.default.instance.init(layers_1.default.toastLayer);
        panelCtrl_1.default.instance.init(layers_1.default.popupLayer);
        sceneCtrl_1.default.instance.init(layers_1.default.sceneLayer);
        // 固定宽
        this.stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;
        this.registerModules();
        this.getData();
        RES.setMaxLoadingThread(10);
        this.runGame().catch(function (e) {
            console.log(e);
        });
    };
    MainBase.prototype.getData = function () { };
    MainBase.prototype.registerModules = function () { };
    MainBase.prototype.runGame = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.loadResource()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, MovieClipCtrl_1.default.instance.init()];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    MainBase.prototype.loadResource = function () {
        return __awaiter(this, void 0, void 0, function () {
            var e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 3, , 4]);
                        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
                        console.log("开始加载配置文件");
                        return [4 /*yield*/, RES.loadConfig("default.res.json", utils_1.getResPath() + "resource/")];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.loadTheme()];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        e_1 = _a.sent();
                        console.error(e_1);
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    MainBase.prototype.loadTheme = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            var theme = new eui.Theme("resource/default.thm.json", _this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, function () {
                resolve();
            }, _this);
        });
    };
    /**
     * 配置文件加载完成,开始预加载Preload资源组。
     */
    MainBase.prototype.onConfigComplete = function (event) {
        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资源组加载完成
     */
    MainBase.prototype.onResourceLoadComplete = function (event) {
        if (event.groupName == "Preload") {
            this.trace("preload组加载完成");
            //this.trace("开始加载Normal资源");
            GDispatcher_1.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资源组加载进度
     */
    MainBase.prototype.onResourceProgress = function (event) {
        // 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}`);
    };
    /**
     * 资源组加载出错
     */
    MainBase.prototype.onResourceLoadError = function (event) {
        this.trace(event.groupName + "\u7EC4\u8D44\u6E90\u52A0\u8F7D\u5931\u8D25");
        //忽略加载失败的项目
        this.onResourceLoadComplete(event);
    };
    /**
     * 资源加载出错
     */
    MainBase.prototype.onResourceItemLoadError = function (event) {
        this.trace("项目加载失败,url : " + event.resItem.url);
    };
    MainBase.prototype.initStateText = function () {
        this.stateText = new egret.TextField();
        this.stateText.size = 22;
        this.stateText.text = this.text;
        this.stateText.width = 480;
        this.addChild(this.stateText);
    };
    MainBase.prototype.trace = function (msg) {
        // this.text = this.text + "\n" + msg;
        // this.stateText.text = this.text;
        egret.log(msg);
    };
    /**
     * 创建场景界面
     * Create scene interface
     */
    MainBase.prototype.createGameScene = function () {
        // GDispatcher.removeEvent('NormalLoaded',this.createGameScene,this);
        console.log('创建开始场景');
    };
    return MainBase;
}(eui.UILayer));
exports.default = MainBase;
__reflect(MainBase.prototype, "\"e:/zqty/egret/libs/tl/MainBase\".MainBase");
//# sourceMappingURL=MainBase.js.map