import { ElMessage } from "element-plus"

type CrimeResVo = { text: string, success: boolean }

const defaultCb = (res: CrimeResVo) => {
    ElMessage({
        message: res.text,
        type: res.success ? 'success' : 'error',
        dangerouslyUseHTMLString: true,
        grouping: true
    })
}

const useItem = (itemId: string, cb = defaultCb) => {
    fetch(window.addRFC("https://www.torn.com/item.php"), {
        "headers": {
            "accept": "*/*",
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
            "sec-ch-ua-mobile": "?0",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "x-requested-with": "XMLHttpRequest"
        },
        "referrer": "https://www.torn.com/item.php",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": `step=useItem&id=${ itemId }&itemID=${ itemId }`,
        "method": "POST",
        "mode": "cors",
        "credentials": "include"
    })
        .then(res => res.json())
        .then(res => cb(res))
        .catch(e => ElMessage({
            message: e.toString,
            type: 'error'
        }));
}

const useItemSync = (itemId: string, showMsg = true, cb = (response: CrimeResVo) => null) => {
    return new Promise((res, rej) => {
        useItem(itemId, (_res) => {
            if (showMsg) defaultCb(_res)
            cb(_res)
            res(null)
        })
    })
}

export default useItem
export { useItemSync }
