import { defineStore } from 'pinia';
import {
    wsInit,
    wsSend,
    wsSetMessageCallback,
    wsRemoveMessageCallback,
    wsRemoveAllMessageCallback,
    wsClose,
    type Response,
    type Request,
    wsSetErrorCallback, wsRemoveAllErrorCallback
} from '@/utils/ws';

export const useWsStore = defineStore('ws', {
    state: () => ({
        isConnected: false,
        lastMessage: null as Response | null,
    }),
    actions: {
        initWebSocket(funish: () => void) {
            wsInit(funish);
            this.isConnected = true;
        },
        setMessageCallback(onMessage: (response: Response) => void) {
            wsSetMessageCallback(onMessage);
        },
        removeMessageCallback(onMessage: (response: Response) => void) {
            wsRemoveMessageCallback(onMessage);
        },
        removeAllMessageCallback() {
            wsRemoveAllMessageCallback();
        },
        setErrorCallback(onError: () => void){
            wsSetErrorCallback(onError);
        },
        removeAllErrorCallback(){
            wsRemoveAllErrorCallback() ;
        },



        sendMessage(request: Request) {
            wsSend(request);
        },

        closeWebSocket() {
            wsClose();
            this.isConnected = false;
        },

    },
});
