import AssetAdapter from "./AssetAdapter";
import PanelCtrl from "./Ctrls/PanelCtrl";
import SceneCtrl from "./Ctrls/SceneCtrl";
import Loading from "./Loading/Loading";
import ThemeAdapter from "./ThemeAdapter";
import TopLayerCtrl from './Ctrls/TopLayerCtrl';
import { getResPath, getAppLocation, getCookie, login } from "./Global/GUtils";
import { customClassPrototype } from "./Components/Custom";
import { Decorator } from "./Decorator/Decorator";
import ToastPanel from "./Components/ToastPanel";
import MProgressBar from "./MUI/MProgressBar";
import MButton from "./MUI/MButton";
import Net from "./Global/Net";
import MainScene from "./Scene/MainScene";
import StartScene from "./Scene/StartScene";
import MTweenMgr from "./components/MTween";
import PhycicsSystem from "./Game/PhycicsSystem";
import Ball from "./Global/Ball";
import { NetUtils } from "./Global/NetUtils";
import MLabel from "./MUI/MLabel";
import { MConfigs } from "./Global/MConfigs";
import { Buried } from "../libs/tw/util/Buried";
import DropBlinkMgr from "./Mgr/DropMgr";
import SpTimer from "./Game/SpTimer";
import SoundMgr from "./Mgr/SoundMgr";
import { MConst } from "./Global/MConst";
import GameMgr from "./Mgr/GameMgr";
import MLayers from "./views/MLayer";

@Decorator.OnUpdate
class Main extends eui.UILayer {
    constructor() {
        super();
        customClassPrototype();
    }

    protected async createChildren() {
        super.createChildren();
        if (getCookie("isNotLoginUser") == "true") {
            await new Promise<void>((resolve, reject) => {
                Net.sendGet(`/ctool/getProjectUserInfo`, undefined, (res) => {
                    window["$"]("body").append(res.data.loginJs);
                    if (window['requirelogin']) {
                        window['requirelogin']();
                        resolve();
                    } else {
                        reject("no function requirelogin");
                    }
                }, () => {
                    reject();
                });
            }).catch(e => { throw e });
            return;
        }


        SpTimer.init();
        MTweenMgr.instance.init();
        PhycicsSystem.init();
        Net.urlReplace();
        MConfigs.updateConfig();
        DropBlinkMgr.init();
        Buried.init(window["appId"], NetUtils.getProjectId());

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

        // egret.ImageLoader.crossOrigin = "anonymous";

        let layers = MLayers.instance;
        layers.init(this);
        Loading.init(layers.topLayer);
        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);
        TopLayerCtrl.instance.init(layers.topLayer);
        ToastPanel.parent = layers.toastLayer;

        //设置屏幕适配方式
        this.stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;

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

        /* document.addEventListener("visibilitychange", function () {
            if (document.visibilityState == "visible") {
                SoundMgr.instance.onResume();
            }
            if (document.visibilityState == "hidden") {
                SoundMgr.instance.onPause();
            }
        }); */
    }

    private async runGame() {
        await this.loadResource()
        GameMgr.instance.isXiamenUser = await this.isXiamenUser();
        this.createGameScene();
    }

    private getAssistItemId() {
        const href = window.location.href;
        const str: string = href.split("assistItemId=")[1];
        if (str) {
            const id = str.split("&")[0];
            if (id != "null") {
                window.localStorage.setItem("unreadAssistId", id);
                window.location.href = href.replace(id, "null");
                return "waiting";
            } else {
                return this.getAssistItemIdFromStorage();
            }
        } else {
            return this.getAssistItemIdFromStorage();
        }
    }

    private getAssistItemIdFromStorage() {
        const id = window.localStorage.getItem("unreadAssistId");
        if (id) {
            window.localStorage.setItem("unreadAssistId", "");
            return id;
        } else {
            return "";
        }
    }

    private async loadResource() {
        try {
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await this.loadTheme();
            await RES.loadGroup("loading");
            await RES.loadGroup("toast_panel");
            await RES.loadGroup("main_scene");
        }
        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 async createGameScene() {
        console.log("CFG", NetUtils.getCFG());
        const id = this.getAssistItemId();
        if (id != "waiting") {
            SceneCtrl.instance.change<StartScene>(StartScene).assistItemId = id;
        }
    }

    private async isXiamenUser() {
        return true;
        let location = new egret.Point();
        location = await getAppLocation();

        return MConst.XiamenLocation.contains(location.x, location.y);
    }
}

window["Main"] = Main;
window["MProgressBar"] = MProgressBar;
window["MButton"] = MButton;
window["MLabel"] = MLabel;
