import { DataManager } from "../libs/tw/manager/DataManager";
import { NetManager } from "../libs/tw/manager/NetManager";
import AssetAdapter from "./AssetAdapter";
import PanelCtrl from "./ctrls/panelCtrl";
import SceneCtrl from "./ctrls/sceneCtrl";
import Loading from "./loading/Loading";
import RulePanel from "./rulePanel/RulePanel";
import ThemeAdapter from "./ThemeAdapter";
import { ModuleTypes } from "./types/sceneTypes";
import { getResPath } from "./utils";
import layers from "./views/layers";
import MainScene from './mainScene/MainScene';
import { PetIndexData } from "../libs/tw/data/pet/PetIndexData";
import MsgPanel from "./msgPanel/MsgPanel";
import SharePanel from './sharePanel/SharePanel';
import { Buried } from '../libs/tw/util/Buried';
import LoadingScene from './loadingScene/loadingScene';
import { GDispatcher } from '../libs/tc/util/GDispatcher';
import StartScene1 from './startScene/StartScene';
import DogShowPanel from './dogShowPanel/DogShowPanel';
import ShopPanel from './shopPanel/ShopPanel';
import TeamScene from './teamScene/TeamScene';
import TopLayerCtrl from './ctrls/topLayerCtrl';
import ToastPanel from './toastPanel/ToastPanel';

class Main extends eui.UILayer {
    protected createChildren(): void {
        super.createChildren();
        // alert(1)

        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.petIndexData = new PetIndexData();
        DataManager.ins.petIndexData.update(window['CFG']);
        // NetManager.ins.getCredits(()=>{});

        layers.init(this);
        Loading.init(layers.topLayer);
        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);
        TopLayerCtrl.instance.init(layers.topLayer);
        
        Buried.init();

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

        PanelCtrl.instance.registerPanelClass(ModuleTypes.MSG_PANEL, MsgPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.DOG_SHOW_PANEL, DogShowPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SHOP_PANEL, ShopPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SHARE_PANEL, SharePanel);

        SceneCtrl.instance.registerSceneClass(ModuleTypes.LOADING_SCENE, LoadingScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.MAIN_SCENE, MainScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.START_SCENE, StartScene1);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.TEAM_SCENE, TeamScene);


        TopLayerCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, ToastPanel);

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

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        // RES.loadGroup("msg", 10);
    }

    private async loadResource() {
        try {
            // const loadingView = new LoadingUI();
            // this.stage.addChild(loadingView);
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await this.loadTheme();

            // await RES.loadGroup("msg", 10);
            // this.stage.removeChild(loadingView);
        }
        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 createGameScene(): void {
        //获取签到信息
        NetManager.ins.getSignInfo(() => {
            NetManager.ins.getShareCode(()=>{
                NetManager.ins.getPetInfo(() => {
                    this.getGameRes();
                }, DataManager.ins.petIndexData.activityId);
            },window["CFG"].activityId,window["activityType"])
        }, window['signActivityId']);

    }

    doShare(){
        var shareData = {
            title: '点击解锁您的北京记忆',//标题
            desc: 'hi，您有一份关于北京电影的专属回忆待查收～结尾还有神秘彩蛋哦！',//描述
            link: "http://activity-2.m.duiba.com.cn/customShare/share?id=2921",//链接
            imgUrl: 'http://video.duiba.com.cn/ts_video/V1905/share.png',//图片
        }
        
        window["wx"].config({
            debug:  window["wx"].$wxdebug,
            appId: '$wxappid',
            timestamp: '$wxtimestamp',
            nonceStr: '$wxnonceStr',
            signature: '$wxsignature',
            jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage']
        });

        window["wx"].onMenuShareTimeline({
            title: shareData.title, //标题
            desc: shareData.desc, //描述
            link: shareData.link, //链接
            imgUrl: shareData.imgUrl, //图片
            success: function () {},
            cancel: function () {}
        });

        window["wx"].onMenuShareAppMessage({
            title: shareData.title, //标题
            desc: shareData.desc, //描述
            link: shareData.link, //链接
            imgUrl: shareData.imgUrl, //图片
            success: function (e) {},
            cancel: function () {}
        });
     
    }

    //加载游戏中的资源
    private async getGameRes(){
        //还没有宠物，先播放介绍文字
        // if (!DataManager.ins.petHomeInfoData.petId) {
        //     await RES.loadGroup('adopte_panel');
        //    // await RES.getResAsync('adopteBg_jpg');
        //     PanelCtrl.instance.show(ModuleTypes.ADOPTE_PANEL);
        //     await RES.loadGroup('guide_component');
        // } else {//已经有宠物了，进入游戏场景
        //     await RES.loadGroup('main_scene');
        //    // await RES.getResAsync('bgday_jpg');
        //     SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
        // }

        await RES.loadGroup('loading_scene');
        SceneCtrl.instance.change(ModuleTypes.LOADING_SCENE);
        setTimeout(() => {
            console.log(5555555);
            GDispatcher.dispatchEvent('progress',[100]);
        }, 200);


        //加载组
        // await RES.loadGroup('signIn_prize_panel');
        // await RES.loadGroup('signIn_panel');
        // await RES.loadGroup('extra_prize_panel');
        // await RES.loadGroup('upPrize_panel');
        // await RES.loadGroup('upNoPrize_panel');
        // await RES.loadGroup('earnGold_panel');
        // await RES.loadGroup('guide_panel');
        // //加载图片
        // await RES.getResAsync('gamerule_jpg');
        // await RES.getResAsync('guideBg_jpg');

    }
}

window['Main'] = Main;