import { contextBridge, ipcRenderer } from 'electron'

// Custom APIs for renderer
const api = {
    getConfig: () => ipcRenderer.invoke('getConfig'),
    setConfig: (config) => ipcRenderer.invoke('setConfig', config),
    listPlugins: () => ipcRenderer.invoke('listPlugins'),
    setActivePlugin: (pluginId) =>
        ipcRenderer.invoke('setActivePlugin', pluginId),
    openNoteWindow: (noteId) => {
        ipcRenderer.send('open-note-window', noteId)
    },
    onNoteCreated: (callback) => {
        ipcRenderer.on('note-created', (_, data) => callback(data))
    },
    onNoteUpdated: (callback) => {
        ipcRenderer.on('note-updated', (_, data) => callback(data))
    },
    onNoteDeleted: (callback) => {
        ipcRenderer.on('note-deleted', (_, data) => callback(data))
    },
    onPluginChanged: (callback) => {
        ipcRenderer.on('plugin-changed', (_, data) => callback(data))
    },
    notifyNoteChanged: (event, data) => {
        ipcRenderer.send('note-changed', event, data)
    },
}

// Implement adapter API - communicates with plugin adapter in main process
const adapter = {
    call: (method, ...args) => ipcRenderer.invoke('adapter:call', method, args),
}

if (process.contextIsolated) {
    try {
        contextBridge.exposeInMainWorld('api', api)
        contextBridge.exposeInMainWorld('adapter', adapter)
    } catch (error) {
        console.error(error)
    }
} else {
    window.api = api
    window.adapter = adapter
}
