import AssetAdapter from "./AssetAdapter";
import PanelCtrl from "./ShootPlanet/MCtrls/MPanelCtrl";
import SceneCtrl from "./ShootPlanet/MCtrls/MSceneCtrl";
import Loading from "./loading/Loading";
import ThemeAdapter from "./ThemeAdapter";
import layers from "./ShootPlanet/MViews/MLayers";
import TopLayerCtrl from './ShootPlanet/MCtrls/MTopLayerCtrl';
import { getResPath, arrayRemove, isWeiXin, wxConfig, getAppLocation, getCookie, invokeWX, login } from "./ShootPlanet/Global/GUtils";
import { customClassPrototype } from "./ShootPlanet/MComponents/Custom";
import { Decorator } from "./ShootPlanet/Decorator/Decorator";
import ToastPanel from "./ShootPlanet/MComponents/MToastPanel";
import MProgressBar from "./ShootPlanet/MUI/MProgressBar";
import MButton from "./ShootPlanet/MUI/MButton";
import Net from "./ShootPlanet/Global/Net";
import MainScene from "./ShootPlanet/Scene/MainScene";
import StartScene from "./ShootPlanet/Scene/StartScene";
import MTimer from "./ShootPlanet/MComponents/MTimer";
import MTweenMgr from "./ShootPlanet/MComponents/MTween";
import PhycicsSystem from "./ShootPlanet/Game/PhycicsSystem";
import Ball from "./ShootPlanet/Global/Ball";
import { NetUtils } from "./ShootPlanet/Global/NetUtils";
import MLabel from "./ShootPlanet/MUI/MLabel";
import { MConfigs } from "./ShootPlanet/Global/MConfigs";
import SoundMgr from "./ShootPlanet/Mgr/SoundMgr";
import DropBlinkMgr from "./ShootPlanet/Game/DropBlinkMgr";
import GameMgr from "./ShootPlanet/Mgr/GameMgr";
import { MConst } from "./ShootPlanet/Global/MConst";
import MBuried from "./ShootPlanet/Global/MBuried";

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

    protected async createChildren() {
        super.createChildren();

        if (!isWeiXin() && getCookie("isNotLoginUser") == "true") {
            await login().catch(e => { throw e });
            // return;

            /* await new Promise(resovle => {
                setTimeout(async () => {
                    
                    resovle();
                }, 60000);
            }) */
        }

        MTimer.init();
        MTweenMgr.instance.init();
        PhycicsSystem.init();
        Net.urlReplace();
        MConfigs.updateConfig();
        DropBlinkMgr.init();
        MBuried.init(MConfigs.appId, NetUtils.getProjectId());

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

        egret.ImageLoader.crossOrigin = "anonymous";

        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;

        //分享链接附加projectId
        if (!isWeiXin())
            window["shareData"].url = "https://wzmmyh.activity-1.m.duiba.com.cn/customShare/share?id=3676&projectId=" + NetUtils.getProjectId();

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

        document.addEventListener("visibilitychange", function () {
            if (document.visibilityState == "visible") {
                if (SoundMgr.instance.musicEnabled) {
                    SoundMgr.instance.playMusic();
                }
            }
            if (document.visibilityState == "hidden") {
                SoundMgr.instance.stopMusic();
            }
        });
    }

    private async runGame() {
        await this.loadResource()
        if (isWeiXin()) {
            await wxConfig();
            invokeWX();
        }
        //判断是否是温州用户
        GameMgr.instance.isWenzhouUser = await this.isWenzhouUser();
        this.createGameScene();
    }

    private async isWenzhouUser() {
        return true;
        let location = new egret.Point();
        if (isWeiXin()) {
            return true;
        } else {
            location = await getAppLocation();
        }

        if (location == null) {
            ToastPanel.show("获取位置超时，当前应该是测试阶段，直接进入游戏");
            return true;
        }

        // console.log("当前位置", location, "杭州矩形", MConst.HangzhouLocation);
        /* return MConst.HangzhouLocation.contains(location.x, location.y)
            || MConst.WenzhouLocation.contains(location.x, location.y); */
        return MConst.WenzhouLocation.contains(location.x, location.y);
    }



    private async loadResource() {
        try {
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await this.loadTheme();
            await RES.loadGroup("loading");
            Loading.instace.show();
            await RES.loadGroup("toast_panel");
            await RES.loadGroup("game");
            await RES.loadGroup("car");
            await RES.loadGroup("animation");
            await RES.loadGroup("sound");
            Loading.instace.hide();
        }
        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());
        SoundMgr.instance.setMusic("bgm_mp3");
        SceneCtrl.instance.change(StartScene);
    }
}

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