import {reactive} from 'vue'
import {PoolData, TimeUnits} from "~/types";
import request from "~/utils/request";
import cookie from "~/utils/cookie";
import {HtyUnionIDToken} from "~/utils";

const store = reactive<{ data: PoolData }>({data: {}})


export default function usePool() {

    function set(data: Partial<PoolData>) {
        store.data ={...store.data, ...(data || {})}
    }

    function setKey(key: keyof PoolData, value: any) {
        store.data[key] = value;
    }

    function getKey(key: keyof PoolData) {
        return store.data[key]
    }

    async function setRemoteCache(key: string,  value?: any, exp = 7, exp_unit = TimeUnits.DAY) {
        let data = value || store.data;
        data.unionid = cookie.get(HtyUnionIDToken)
        data.time = new Date()
        try {
            const {r, d, e} = await request({
                url: "/api/v1/uc/save_cached_kv", method: "post", data: {key, val: JSON.stringify(data), exp, exp_unit}
            })
            if (!r) {
                console.error("set cached kv failed...", e)
            }
        } catch (e) {
            console.error("set remote cache error...", e)
        }
    }

    async function getRemoteCache(key: string){
        try {
            const {r, d, e} = await request({
                url: "/api/v1/uc/get_cached_kv/" + key
            });
            if (!r) {
                console.error("get cached kv failed...", e)
            }
            return d;
        } catch (e) {
            console.log("get remote cache error...", e)
        }
    }

    async function delRemoteCache(key: string){
        try {
            const {r, d, e} = await request({
                url: "/api/v1/uc/del_cached_kv/" + key
            });
            if (!r) {
                console.error("del cached kv failed...", e)
            }
            return d;
        } catch (e) {
            console.log("del remote cache error...", e)
        }
    }

    function get() {
        return store.data;
    }

    function remove(key: keyof PoolData) {
        store.data[key] = undefined;
    }

    function clear() {
        store.data = {}
    }

    return {set, setKey, get, remove, clear, getKey, setRemoteCache, getRemoteCache, delRemoteCache}
}
