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;
    }
}

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

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