import { MUtils } from "./MUtils";
import { MConst } from "./MConst";
import { MConfigs } from "./MConfigs";
import Net from "./Net";
import { NetUtils } from "./NetUtils";
import difficultyFactor = MConfigs.difficultyFactor;

export const getResPath = () => window['resPath'] || '';
export const getSkinPath = (key: any) => `resource/skins/${key}Skin.exml`

let shareImg: HTMLElement = null;
export function setShareImg(imgUrl: string, rect: engine.Rectangle, visible: boolean = true) {
    shareImg = shareImg || document.getElementById('shareImg');
    shareImg.style.position = 'absolute';
    shareImg.style.display = 'block';
    shareImg.style.visibility = "visible";
    shareImg.style.opacity = visible ? "1" : "0";
    let scaler = document.body.clientWidth / 750;
    shareImg.style.width = (scaler * rect.width).toString() + "px";
    shareImg.style.height = (scaler * rect.height).toString() + "px";
    shareImg.style.left = (rect.x * scaler).toString() + "px";
    shareImg.style.top = (rect.y * scaler).toString() + "px";
    shareImg['src'] = imgUrl;
}
export function clearShareImg() {
    if (!shareImg) {
        console.log("shareImg is null");
        return;
    }

    shareImg.style.width = "0px";
    shareImg.style.height = "0px";
    shareImg.style.visibility = "hidden";
}

export function getBallScore(bulletScore: number, powerScore: number, colorIndex: number): any {
    let diff = difficultyFactor;

    let getScoreFromRange = ([a, b]) => {
        a = Math.ceil(a * 0.0001);
        b = Math.ceil(b * 0.0001);
        let n = Math.abs(b - a) + 1;
        n = Math.floor(n / 6);
        const m = [];
        for (let i = 0; i < 5; i++) {
            m.push([a + n * i, a + n * i + n - 1]);
        }
        m.push([a + n * 4 + n, b])
        const [a0, b0] = m[colorIndex]; //1-10
        let result = Math.ceil(Math.random() * (b0 - a0 + 1)) + a0
        return result;
    }

    if (bulletScore <= 20)
        return getScoreFromRange([0.01 * powerScore, 0.2 * powerScore]);

    if (bulletScore > 20 && bulletScore <= 40) {
        return getScoreFromRange([0.2 * powerScore, 0.6 * powerScore]);
    }

    let getRange = (list: any[], props: any[]) => {
        return getScoreFromRange(getProp(list, props)[0]);
    }

    if (bulletScore > 40 && bulletScore <= 60) {
        const list = [
            [0.2 * powerScore, 0.6 * powerScore],
            [0.6 * powerScore, 0.8 * powerScore],
            [0.8 * powerScore, 1.5 * powerScore],
        ]
        return getRange(list, [3, 5, 2]);
    }
    if (bulletScore > 60 && bulletScore <= 80) {
        const list = [
            [0.6 * powerScore, 0.8 * powerScore],
            [0.8 * powerScore, 1.5 * powerScore],
            [1.5 * powerScore, 2.2 * powerScore],
        ]
        return getRange(list, [2, 5, 2]);
    }

    if (bulletScore > 80 && bulletScore <= 100) {
        const list = [
            [1.5 * powerScore, 2.2 * powerScore],
            [2.2 * powerScore, 3.2 * powerScore],
            [3.2 * powerScore, 4.2 * powerScore],
        ]
        return getRange(list, [1, 5, 4]);
    }

    if (bulletScore > 100 && bulletScore <= 120) {
        const list = [
            [2.2 * powerScore, 3.2 * powerScore],
            [3.2 * powerScore, 4.2 * powerScore],
            [4.2 * powerScore, 5.2 * powerScore],
        ]
        return getRange(list, [1, 4, 5]);
    }

    const list = [
        [2.2 * powerScore, 3.2 * powerScore],
        [3.2 * powerScore, 4.2 * powerScore],
        [4.2 * powerScore, 5.2 * powerScore],
    ]
    return getRange(list, [1, 3, 6]);
}

export function getProp(items: any[], props: number[], n = 1) {
    let pool = [];
    for (let i in items) {
        for (let j = 0; j < props[i]; j++) {
            pool.push(items[i]);
        }

    }

    const result = [];
    for (let i = 0; i < n; i++) {
        result.push(pool[MUtils.randomInt(0, pool.length)]);
    }
    return result;
}


export function createPropsCard(id: string): engine.Container {
    let bgUrl = "score_card_bg_png";
    if (id == MConst.ReviveCardId) {
        bgUrl = "revive_card_bg_png"
    }

    let group = new engine.Container();
    group.addChild(new engine.Image(RES.getRes(bgUrl)));
    let label = new engine.Label();
    label.text = MConfigs.props[id].name;
    label.fillColor = 0x0a703e;
    label.size = 24;
    label.offsetX = 0;
    label.offsetY = 0;
    group.addChild(label);

    return group;
}

export function getPropsTypeName(type: 0 | 1): string {
    switch (type) {
        case 0: return "原地复活卡";
        case 1: return "加分卡";
        default: return null;
    }
}

export function restart() {
}

export function arrayRemove(array: any[], target: any): any[] {
    let newArray = [];
    for (let i = 0; i < array.length; i++) {
        if (array[i] !== target) {
            newArray.push(array[i]);
        }
    }
    return newArray;
}

export function isWeiXin() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i)) {
        return true
    } else {
        return false
    }
}

export function wxConfig(): Promise<void> {
    return new Promise<void>(resolve => {
        Net.sendGet("/wechatShare/getShareInfo/v2", {
            wxdebug: false,
            url: window.location.href
        }, (res) => {
            wx.props({
                debug: false,
                appId: res.wxappid,
                timestamp: res.wxtimestamp,
                nonceStr: res.wxnonceStr,
                signature: res.wxsignature,
                jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage']
            });

            wx.error(function (res: any) {
                console.error("wx error", res);
            });

            wx.ready(function () {
                resolve();
            });
        }, () => { resolve(); });
    });
}

export function invokeWX(onSuccess?: () => void, onCancel?: () => void) {
    let share = window["shareData"];
    wx.onMenuShareTimeline({
        title: share.title,
        desc: share.desc,
        link: share.url + NetUtils.getProjectId(),
        imgUrl: share.imgUrl,
        success: function () {
            onSuccess && onSuccess();
        },
        cancel: function () {
            onCancel && onCancel();
        }
    });

    wx.onMenuShareAppMessage({
        title: share.title,
        desc: share.desc,
        link: share.url + NetUtils.getProjectId(),
        imgUrl: share.imgUrl,
        success: function () {
            onSuccess && onSuccess();
        },
        cancel: function () {
            onCancel && onCancel();
        }
    });
}


export function getAppLocation() {
    return new Promise<engine.Point>((resolve, reject) => {
        window["getClientLocation"] = function (latitudeC: number, longitudeC: number) {
            resolve(new engine.Point(longitudeC, latitudeC));
        };

        setTimeout(() => {
            resolve(null);
        }, 1000);
        window["App"].getLocation();
    });
}

export function getCookie(cookieName: string) {
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for (var i = 0; i < arrCookie.length; i++) {
        var arr = arrCookie[i].split("=");
        if (cookieName == arr[0]) {
            return arr[1];
        }
    }
    return "";
}


export function login() {
    return new Promise<void>((resolve, reject) => {
        Net.sendGet(`/ctool/getProjectUserInfo`, undefined, (res) => {
            window["$"]("body").append(res.data.loginJs);
            if (window['requirelogin']) {
                window['requirelogin']();
                resolve();
            } else {
                reject("no function requirelogin");
            }
        }, () => {
            reject();
        });
    })
}




