import type { IpcRenderer, IpcRendererEvent } from 'electron'
import type { UseIpcRendererReturn } from '@vueuse/electron'
import { useIpcRenderer } from '@vueuse/electron'

const ipc = useIpcRenderer()

export type IpcRendererListener = (event: IpcRendererEvent, ...args: any[]) => void

export interface UserIpcRendererRetrun extends UseIpcRendererReturn {
    invokeAsync<T>(channel: string, ...args: any[]): Promise<T | null>
}

export interface UseElectronReturn {
    ipcRenderer: UserIpcRendererRetrun
}

export function useElectron(ipcRenderer?: IpcRenderer): UseElectronReturn {
    if (!ipcRenderer) ipcRenderer = window?.require('electron').ipcRenderer

    if (!ipcRenderer) throw new Error('provide IpcRenderer module or enable nodeIntegration')

    return {
        ipcRenderer: {
            on: ipc.on,
            once: ipc.once,
            removeListener: ipc.removeListener,
            removeAllListeners: ipc.removeAllListeners,
            send: ipc.send,
            sendSync: ipc.sendSync,
            sendTo: ipc.sendTo,
            sendToHost: ipc.sendToHost,
            postMessage: ipc.postMessage,
            invoke: ipc.invoke,
            invokeAsync: <T>(channel: string, ...args: any[]): Promise<T> => ipcRenderer.invoke(channel, ...args),
        },
    }
}
