// https://stackoverflow.com/questions/46946380/fetch-api-request-timeout
// https://developer.mozilla.org/zh-CN/docs/Web/API/AbortSignal#%E8%B6%85%E6%97%B6%E6%88%96%E6%98%BE%E5%BC%8F%E4%B8%AD%E6%AD%A2_fetch

import { log, path } from "cc"
import { PREVIEW } from "cc/env"

const gameId = "rp_11001";
// let apiaddr = "https://rpgames-api.rpfafafahkdev.com";
let apiaddr = "";
let token = "eyJQIjoxMDIyNDksIkUiOjE3NjM1Nzk2NTIsIlMiOjk5OSwiRCI6InJwXzExMDAxIn0.7Z8z7XOUvp3XU795wRfy4CrgXZBD38w1mAYErFufAWw";


let language = "en"
let currency = "THB"
let csymbol = ""
let fromUrl = ""
let supportUrl = ""
let oddsUrl = ""
let historyUrl = ""
let isRB7 = false;

export function getOddsUrl() {
    return oddsUrl;
}

export function getSupportUrl() {
    return supportUrl;
}

export function getHistoryUrl() {
    return historyUrl;
}

export function getLanguage() {
    // return 'my';
    return language;
}

export function getIsRB7() {
    // return true;
    return isRB7;
}

export function getFromUrl() {
    return fromUrl;
}

export function getCsymbol() {
    return csymbol;
}

export function initReqAddr() {
    let partHost = ".rpfafafahkdev.com";
    if (!PREVIEW) {
        const qs = new URLSearchParams(location.search)

        token = qs.get("t");
        const l = qs.get("l");
        if (l) {
            language = l
        }

        const c = qs.get("c");
        if (c) {
            currency = c
        }

        // brand=rb7
        const rb7 = qs.get("brand");
        if (rb7) {
            isRB7 = rb7 == "rb7";
        }

        const f = qs.get("from");
        if (f) {
            fromUrl = f;
        }

        const csy = qs.get("csymbol");
        if (csy) {
            csymbol = csy
        }

        const dotidx = location.host.indexOf('.')
        partHost = location.host.slice(dotidx)
    }

    apiaddr = `https://rpgames-api${partHost}`
    supportUrl = `https://rpgames-intro${partHost}/#/index?gid=${gameId}&type=support&l=${language}&c=${currency}`
    oddsUrl = `https://rpgames-intro${partHost}/#/index?gid=${gameId}&type=odds&l=${language}&c=${currency}`
    historyUrl = `https://rpgames-intro${partHost}/#/history?gid=${gameId}&l=${language}&c=${currency}&t=${token}`
}

AbortSignal.timeout ??= function timeout(ms) {
    const ctrl = new AbortController()
    setTimeout(() => ctrl.abort(), ms)
    return ctrl.signal
}

export async function callGameApi(action: string, argsObj: any) {
    const url = apiaddr + path.join("/gameapi/", gameId, action)
    const payload = JSON.stringify(argsObj)

    const res = await fetch(url, {
        signal: AbortSignal.timeout(10000),
        headers: {
            "Content-Type": "application/json",
            "X-Rp-Token": token,
        },
        method: "POST",
        body: payload,
        mode: 'cors',
    })

    if (res.status != 200) {
        const errstr = await res.text()
        throw new Error(errstr || res.statusText)
    }
    const obj = await res.json()
    return obj
}

let uploadErrorSeq = 0
export async function uploadError(msg: string) {
    if (uploadErrorSeq > 1000) {
        return
    }

    const argsObj = {
        "game": gameId,
        "type": "error",
        "href": window.location.href,
        "userAgent": window.navigator.userAgent,
        "language": language,
        "currency": currency,
        "token": token,
        "msg": msg,
        "seq": uploadErrorSeq++,
    }


    const url = apiaddr + "/event/upload"
    const payload = JSON.stringify(argsObj)

    const res = await fetch(url, {
        signal: AbortSignal.timeout(10000),
        method: "POST",
        body: payload,
        mode: 'cors',
    })

    console.log("uploadError", "statusText", res.statusText)
}

export function gold2cash(v: number): string {
    v /= 10000
    return v.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}



export function gold2cash2(v: number): string {
    v /= 10000
    if (v % 1 == 0) {
        return v.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    } else {
        return v.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }

}

export async function getHistory(argsObj: any) {

    // https://rpgames-api.rpfafafahkdev.com/gameapi/rp_11001/gameinfo
    // https://rpgames-api.rpfafafahkdev.com/gameapi/history

    // const resp = await callGameApi("history", argsObj)

    // callGameApi 会多拼一截gameId , history单独写
    const url = apiaddr + path.join("/gameapi/", "history")
    const payload = JSON.stringify(argsObj)

    const res = await fetch(url, {
        signal: AbortSignal.timeout(10000),
        headers: {
            "Content-Type": "application/json",
            "X-Rp-Token": token,
        },
        method: "POST",
        body: payload,
        mode: 'cors',
    })

    if (res.status != 200) {
        const errstr = await res.text()
        throw new Error(errstr || res.statusText)
    }
    const obj = await res.json()
    return obj
}


export function getCurrency() {
    // return 'THB';
    return currency;
}

