import type { BrowserWindow } from 'electron'
import type { SettingStore } from '/#/store'

import Store from 'electron-store'
import { ipcMain } from 'electron'
import { autoUpdater } from 'electron-updater'
import { machineIdSync } from 'node-machine-id'
import { app } from './config'

export async function useStore(_win: BrowserWindow) {
    // 初始化配置
    const store = new Store<SettingStore>({
        name: app.name,
        encryptionKey: app.key,
        clearInvalidConfig: true,
        defaults: {
            system: {
                // 机器码
                machineId: machineIdSync().toUpperCase(),
                // 调试模式
                debug: app.debug,
                // 是否总在最前
                alwaysOnTop: false,
                // 检查更新地址
                feedURL: '',
            },
        },
    })

    // ==================== ipc handle ===================
    // 获取配置
    ipcMain.handle('store:get', (_, key) => {
        return store.get(key)
    })
    // 设置配置
    ipcMain.handle('store:set', (_, key, value) => {
        if (key === 'system') {
            const oldValue = store.get(key)
            if (oldValue?.feedURL !== value.feedURL) {
                try {
                    // 设置更新地址
                    autoUpdater.setFeedURL({
                        provider: 'generic',
                        url: value.feedURL,
                    })
                } catch (_) {}
            }
        }

        store.set(key, value)
        console.debug('store:set', key, value)
    })
    // 重置配置
    ipcMain.handle('store:reset', (_, keys) => {
        store.reset(keys)
    })

    return store
}
