import request from "~/utils/request";
import {Daka, Jihua} from "~/types";
import {is_equal} from "~/utils";

export interface SessionData {
    type: "JIHUA" | "DAKA",
    data: Jihua | Daka,
    snapshot: string
}

const store: {session: null | SessionData} = {
    session: null
}

export default function useSession() {


    const write = (type: "JIHUA" | "DAKA", data: Jihua | Daka) => {
        store.session = {type, data, snapshot: JSON.stringify(data)}
    }

    const clear = () => {
        console.log("clear...")
        store.session = null
    }

    const exists = () => {
        return store.session && store.session.type && store.session.data
    }

    const sync = async () => {
        if (!store.session) return;
        let { type, data, snapshot } = store.session;
        if (is_equal(data, JSON.parse(snapshot))) return;
        switch (type) {
            case "JIHUA":
                await request({url: `/api/v1/ws/update_jihua`, data, method: 'POST'});
                break;
            case "DAKA":
                await request({url: `/api/v1/ws/update_daka`, data, method: 'POST'});
                break;
        }
    }

    return {write, sync, clear, exists}

}
