import { Buried } from "../libs/tw/util/Buried";
import { DataManager } from "../libs/tw/manager/DataManager";
import { NetManager } from "../libs/tw/manager/NetManager";
import { IExposureData } from "../libs/tw/data/common/IExposureData";

export namespace MUtils {
    export function setButtonImage(button: eui.Button, texture: egret.Texture) {
        for (let i of button.$children) {
            if (i instanceof eui.Image) {
                i.source = texture;
                return;
            }
        }
        console.error("can not get image in the button");
    }

    const imageCache: { [key: string]: egret.Texture } = {}
    const loadImageCache: { [key: string]: egret.ImageLoader } = {}
    export function loadImage(url: string) {
        if (!url) {
            console.error("empty url");
            return;
        }

        return new Promise<egret.Texture>((resolve) => {
            if (imageCache[url]) {
                resolve(imageCache[url]);
                return;
            }

            if (loadImageCache[url]) {
                loadImageCache[url].once(egret.Event.COMPLETE, (event: egret.Event) => {
                    if (imageCache[url]) {
                        resolve(imageCache[url]);
                    } else {
                        console.error("get image cache fail");
                    }
                }, this);
            } else {
                let imgLoader: egret.ImageLoader = new egret.ImageLoader();
                imgLoader.once(egret.Event.COMPLETE, (event: egret.Event) => {
                    let loader: egret.ImageLoader = event.currentTarget;
                    let texture = new egret.Texture();
                    texture.bitmapData = loader.data;
                    imageCache[url] = texture;
                    resolve(texture);
                }, this);
                imgLoader.load(url);

                loadImageCache[url] = imgLoader;
            }
        });
    }

    function doBuried(appIdParam: string, netManager: NetManager, callback: string) {
        //初始化埋点数据
        Buried.init();
        var appId = DataManager.ins.customCfgData.appId;
        var oaId = DataManager.ins.customCfgData.oaId;
        let data = Buried.createExposure(appId + `.110.${appIdParam}.1`, `202.${oaId}.0.0`);
        netManager[callback](data);
        console.log("exposure", data);
    }
    export function doClickBuried(appIdParam: string) {
        doBuried(appIdParam, NetManager.ins, "clickLog");
    }
    export function doShowBuried(appIdParam: string) {
        doBuried(appIdParam, NetManager.ins, "showLog");
    }
    export let fixAreaRatio = 1;
}