
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();


    clientStore.ipc.on(icpList.socket.connect, async (event, result) => {
        socket.value = null
    })

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


    async function disconnectSocket(){
        if(!clientStore.isClient) return;
        await  new  Promise((resolve,reject)=>{
            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;
        console.log('sendMessage');
        console.log(data);
        new  Promise((resolve,reject)=>{
            clientStore.ipc.removeAllListeners(icpList.socket.sendMessage);
            clientStore.ipc.send(icpList.socket.sendMessage,JSON.stringify(data));

        })
    }





    return {
        sendMessage,
        connectSocket,
        disconnectSocket,
    }
});

export default socket;
