
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import client from "@/stores/modules/client";
import  icpList from '@/utils/ipc'


const socket = defineStore('socket', ()=>{
    const socket = ref(null);
    const clientStore = client();

    async function connectSocket(){
        if(!clientStore.isClient) return;
        new  Promise((resolve,reject)=>{
            if(socket) resolve(socket)
            clientStore.ipc.removeAllListeners(icpList.socket.connect);
            clientStore.ipc.send(icpList.socket.connect);
            clientStore.ipc.on(icpList.socket.connect, async (event, result) => {
                socket.value = result
                resolve(result)
            })

        })
    }



    async function disconnectSocket(){
        if(!clientStore.isClient) return;
        new  Promise((resolve,reject)=>{
            if(socket) resolve(socket)
            clientStore.ipc.removeAllListeners(icpList.socket.disconnect);
            clientStore.ipc.send(icpList.socket.disconnect);
            clientStore.ipc.on(icpList.socket.connect, async (event, result) => {
                socket.value = null
                resolve(result)
            })

        })
    }


    async function sendMessage(data){
        if(!clientStore.isClient) return;
        new  Promise((resolve,reject)=>{
            if(socket) resolve(socket)
            clientStore.ipc.removeAllListeners(icpList.socket.sendMessage);
            clientStore.ipc.send(icpList.socket.sendMessage,JSON.stringify(data));
            clientStore.ipc.on(icpList.socket.sendMessage, async (event, result) => {
                resolve(result)
            })

        })
    }





    return {
        sendMessage,
        connectSocket,
        disconnectSocket,
    }

});

export default socket;
