


import { EventDispatcher } from "../events/EventDispatcher";
import { getCreateImage } from "../utils";

/**
 * 加载器，不做缓存判断，所有的外部自行缓存，或者判断是否要进加载器
 */
export class Loader extends EventDispatcher {

    /**
     * 记录原始数据，json和image，贴图在建立时会被缓存
     * 需要缓存的都用在回调里自行缓存，比如弄个RES
     */
    private caches = {};

    /**
     * 
     */
    constructor() {
        super();
        this._instanceType = "Loader";
    }

    /**
     * 
     * @param callback 
     * @param url 图集一般是png格式,传的是json,在callback自行拆分
     */
    loadSheet(callback: Function, url: string) {
        let pngFile = url.substring(0, url.lastIndexOf('.')) + '.png';
        this.loadImage((suc, data) => {
            if (suc) {
                this.cache(pngFile, data);
                if (this.caches[url]) {
                    callback(true, { json: this.caches[url], img: data })
                    //已回调,释放置空
                    this.caches[url] = null;
                    this.caches[pngFile] = null;
                }
            } else {
                callback(false, data)
            }
        }, pngFile);


        this.loadJson((suc, data) => {
            if (suc) {
                this.cache(url, data);
                if (this.caches[pngFile]) {
                    callback(true, { json: data, img: this.caches[pngFile] });
                    //已回调,释放置空
                    this.caches[url] = null;
                    this.caches[pngFile] = null;
                }
            } else {
                callback(false, data)
            }
        }, url)

        //暂时先不用fetch。safari兼容问题
        // fetchAsync(url)
        //     .then((data) => {
        //         this.cache(url, data);
        //         if (this.caches[pngFile]) {
        //             callback(true, { json: data, img: this.caches[pngFile] })
        //         }
        //         // console.log(data)
        //     })
        //     .catch(reason => {
        //         callback(false, reason)
        //         // console.log(reason.message)
        //     })
    }
    loadJson(callback, url) {
        //@ts-ignore
        my.request({
            url: url,
            dataType: "json",
            success: (res) => {
                callback(true, res.data)
            },
            fail: function (res) {
                // my.alert({
                //   title: JSON.stringify(res)
                // });
                callback(false, res)
            }
        });
    }

    loadImage(callback: (s: boolean, image?: HTMLImageElement) => void, url) {
        let createImage = getCreateImage();
        // // my.alert({
        // //   title: !!createImage
        // // });
        if (!createImage) {
            callback(false);
            return
        }
        let img = createImage();
        //之前的劫持下
        // window["Image"] = function () {
        //     var image = canvas.createImage()
        //     return image
        // }
        // let img = new Image()
        img.onload = function () {
            callback(true, img);
        }
        img.onerror = function () {
            callback(false);
        }
        if (url.indexOf('data:') !== 0) img.crossOrigin = "anonymous";
        img.src = url;
    }
    /**
     * 加载小程序的音频
     * @param callback 
     * @param url 
     */
    loadAudio(callback: (s: boolean, audio?) => void, url) {
        //@ts-ignore
        const innerAudioContext = my.createInnerAudioContext()
        // innerAudioContext.autoplay = true
        innerAudioContext.src = url;
        innerAudioContext.onCanplay(() => {
            callback(true, innerAudioContext)
        })
        // innerAudioContext.onPlay(() => {
        //     console.log('开始播放')
        // })
        innerAudioContext.onError((res) => {
            // console.log(res.errMsg)
            callback(false)
        })
        // innerAudioContext.onEnded(() => {
        //     console.log('播放结束')
        // })
    }



    private cache(name: string, data: any) {
        if (this.caches[name]) {
            console.log("覆盖原先数据：" + name);
        }
        this.caches[name] = data
    }


}

export const GlobalLoader = new Loader();
  //https://yun.duiba.com.cn/db_games/activity/yilian0726/1565580040/resource/result/resultAlta1.json
    //"https://yun.duiba.com.cn/db_games/activity/etc/optionImages/%E5%8D%8E%E4%B8%BAP30.jpg"