

import { layers, destroyLayers } from "../module/views/layers";
import { RES } from "../module/RES";
import { changeScene, destroyAllCtrls } from "../module/ctrls";

import { ResJson } from "./ResJson";
import { destroyNetData } from "./TaoBaoNet";
import { SkinJson } from "./SkinJson";
import { G_EVENT } from "./common/G_EVENT";
import { LoadingScene } from "./scene/LoadingScene";
import { PlayScene } from "./scene/PlayScene";


/**
 * 全局事件，为了和小程序交互
 * 有可能多处页面用到，所以单开
 */
export const GDispatcher = new FYGE.EventDispatcher();

export class Main {
    //主舞台
    stage: FYGE.Stage;
    private requestID;
    private _pause: boolean;
    private canvas: HTMLCanvasElement
    constructor(canvas: HTMLCanvasElement) {
        var sysInfo;
        //@ts-ignore 存在my就初始化
        if (my) {
            FYGE.initedByCanvas(canvas)

            //@ts-ignore 存在my就初始化
            sysInfo = my.getSystemInfoSync()
        }
        //建舞台
        var stage = new FYGE.Stage(
            canvas,
            750,//设计宽度，按设计搞给的就行
            1624,//设计高度
            sysInfo && sysInfo.windowWidth || document.body.clientWidth,
            sysInfo && sysInfo.windowHeight || document.body.clientHeight,
            FYGE.RENDERER_TYPE.CANVAS
        );
        this.stage = stage;
        this.canvas = canvas;//赋值下，为了下面的destroy的cancelAnimationFrame
        //开始循环
        // FYGE.Stage.flushAll();
        //stage初始化
        stage.addEventListener(FYGE.Event.INIT_STAGE, this.onAddToStage, this);
        //帧率
        // var stats = new FYGE.Stats("canva4stats");
        //循环
        var self = this;
        // console.log(FYGE)
        loop();
        function loop() {
            if (!self._pause) {
                // stats.begin();
                FYGE.Tween.flush()
                stage.flush();
                // stats.end();
            }
            //@ts-ignore
            // self.requestID = FYGE.getRequestAnimationFrame()(loop);
            //为了兼容多page的canvas
            my ? self.requestID = canvas.requestAnimationFrame(loop) :
                self.requestID = window.requestAnimationFrame(loop);
        }
    }

    private async onAddToStage() {
        //初始化层级
        layers.init(this.stage);
        console.log("初始化层级完成")
        //初始化资源配置
        RES.loadConfig(ResJson);
        console.log("初始化资源配置完成")
        //皮肤配置加载
        RES.loadSkinConfig(SkinJson);
        //加载通用资源
        await RES.loadGroup("common");
        console.log("通用资源加载完成")
        //隐藏加载中
        // if (document.getElementById("__loading__")) document.getElementById("__loading__").style.display = "none";
        //打开开始场景
        changeScene(LoadingScene);
        // changeScene(PlayScene, {chapter: 120})
    }

    //在小程序显示时调用onShow
    run() {
        this._pause = false;
        //@ts-ignore Tween计时清零
        FYGE.Tween._lastTime = null;

        GDispatcher.dispatchEvent({ type: G_EVENT.ON_SHOW });
    }
    //在小程序隐藏时调用onHide
    pause() {
        // this._pause = true;//先不暂停了
        GDispatcher.dispatchEvent({ type: G_EVENT.ON_HIDE });
    }

    /**
     * 添加全局事件，用于小程序的交互调用
     * 一直很犹豫要不要放在main的实例里，还是和Main同级导出，还有上面的pause，run，下面的事件等
     * @param name
     * @param fun
     * @param thisObj
     * @param once
     */
    addGlobalEvent(name: string, fun: Function, thisObj?: any, once: boolean = false) {
        if (once) {
            GDispatcher.once(name, fun, thisObj)
        } else {
            GDispatcher.addEventListener(name, fun, thisObj)
        }
    }
    /**
     * 派发全局事件，用于小程序的交互调用
     * @param name 可以是事件名，也可以是事件
     * @param data
     */
    dispatchGlobalEvent(name: string | any, data?: any) {
        GDispatcher.dispatchEvent(name, data)
    }
    /**
     * 移除全局事件，用于小程序交互调用
     * @param name
     * @param fun
     * @param thisObj
     */
    removeGlobalEvent(name: string, fun: Function, thisObj?: any) {
        GDispatcher.removeEventListener(name, fun, thisObj)
    }


    //在小程序页面卸载时调用onUnload，多次销毁后会有问题，再检查
    destroy() {
        //Tween都移除，注意吧，可能原先的也被移除
        FYGE.Tween.removeAllTweens()
        // removeAllTimeoutId();//这个再看，尽量用tween的修改
        //停掉计时器
        // FYGE.getCancelAnimationFrame()(this.requestID);
        //@ts-ignore 为了兼容多page的canvas
        my ? this.canvas.cancelAnimationFrame(this.requestID) :
            window.cancelAnimationFrame(this.requestID);
        //层级销毁
        destroyLayers()
        //销毁控制器
        destroyAllCtrls();
        //舞台销毁
        this.stage.destroy();
        //全局事件置空
        GDispatcher.removeAllEventListener();
        //网络数据记录清空
        destroyNetData();
    }
}



function createNineTextures(imageUrl): Promise<FYGE.Texture[]> {
    return new Promise((resolve, reject) => {
        let image = new Image();
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function () {
            var obj = {}
            //名字。
            var name = "lalala";
            var row = 4, col = 3;
            var w = image.width / col;
            var h = image.height / row;

            //生成9张图的数据
            for (var i = 0; i < col * row; i++)
                obj[name + i] = {
                    "x": i % col * w,
                    "y": ~~(i / col) * h,
                    w, h, sw: w, sh: h, ox: 0, oy: 0, ro: false
                };
            FYGE.createTextureSheet(new FYGE.BaseTexture(image), obj);
            //取TextureCache里的
            var arr = [];
            for (var i = 0; i < col * row; i++)arr.push(FYGE.TextureCache[name + i])
            resolve(arr)
        }
        image.onerror = function (err) {
            reject(err)
        }
        image.src = imageUrl
    })
}
