import { GMath } from './GMath';
import { GTime } from './GTime';
import { GConsole } from './GConsole';

export class GFun {
    /**
     * 加载 html Image
     * @param url
     * @param callback
     */
    public static loadImage(url: string, callback: Function): any {
        //取出跟url匹配的Image
        const bitmapData: any = new Image();
        bitmapData.onload = (e) => {
            if (callback) {
                callback(bitmapData);
            }
        };
        bitmapData.src = url;
    }

    /**
     * 替换字符串中元素
     * @param str 
     * @param replaceList
     */
    public static replace(str: string, replaceList: Array<string | number>) {
        const len = replaceList.length;
        for (let i = 0; i < len; i++) {
            str = str.replace("{" + i + "}", replaceList[i].toString());
        }
        return str;
    }

    /**
     * 是否在app内运行
     * @param strs 匹配字符串
     */
    public static checkInApp(strs: string[]): boolean {
        const ua = navigator.userAgent.toLocaleLowerCase();
        let i: number;
        const len: number = strs.length;
        for (i = 0; i < len; i++) {
            if (ua.indexOf(strs[i]) != -1) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断操作系统
     * @returns {Array|{index: number, input: string}}
     */
    public static get isIOS(): boolean {
        return navigator.userAgent.match(/iphone|ipod|ipad/gi) != null;
    }

    /**
     * 获取url参数
     */
    public static getQueryString(name): any {
        const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        const r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }
}

const check_webp_feature = (callback) => {
    const _support_webp_ = localStorage.getItem('_support_webp_');
    if (_support_webp_ !== null) {
        return callback(_support_webp_ === '1')
    }
    const img = new Image();
    img.onload = function () {
        const result = (img.width > 0) && (img.height > 0);
        callback(result);
        localStorage.setItem('_support_webp_', result ? '1' : '0')
    };
    img.onerror = function () {
        callback(false);
        localStorage.setItem('_support_webp_', '0')
    };
    img.src = "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA";
}

export const getImgURL = (url: string):any => {
    return new Promise((resolve, reject) => {
        check_webp_feature((isSupport) => {
            if (isSupport) url += '?x-oss-process=image/format,webp';
            resolve(url);
        })
    })

}