// 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_10012";
const qs = new URLSearchParams(location.search)

// let apiaddr = "https://rpgames-api.rpfafafahkdev.com";
let apiaddr = "";
let token = "eyJQIjoxMDA5NDksIkUiOjE3NjQ3Njk0MjAsIlMiOjk5NiwiRCI6InJwXzEwMDEyIn0.DhDHrfx7WNRBG6D0f5eevBqXg4GubW7_XlxIFUG5L6s";
let language = "en"
let currency = "THB"
let isfrom = null
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 getIsFrom() {
    // return null;
    return isfrom;
}
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
        }

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

        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
}

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, ',');
    }

}