import type { ISystem } from '/#/store'

import { defineStore } from 'pinia'
import { store } from '/@/store'
import { useElectron } from '@/hooks/electron/useElectron'

const { ipcRenderer: ipc } = useElectron()

export const useClientStore = defineStore('app-client', () => {
    const system = ref<ISystem>({})

    async function init() {
        await getSystem()
    }

    async function getSystem() {
        system.value = await ipc.invokeAsync<ISystem>('store:get', 'system')
        return system.value
    }

    function setSystem(value: ISystem) {
        // 保留 machineId 不允许修改
        system.value = { ...value, machineId: system.value.machineId }
        ipc.invoke('store:set', 'system', toRaw(system.value))
    }

    function setDebug(debug: boolean): void {
        ipc.invoke('store:set', 'system.debug', debug)
    }

    function setAlwaysOnTop(alwaysOnTop: boolean): void {
        system.value.alwaysOnTop = alwaysOnTop
        ipc.invoke('store:set', 'system.alwaysOnTop', alwaysOnTop)
    }

    async function reset(...keys: ['system']) {
        await ipc.invokeAsync('store:reset', keys)
        await init()
    }

    // 初始化
    init()

    return {
        system,

        getSystem,
        setSystem,

        setDebug,
        setAlwaysOnTop,

        reset,
    }
})

// Need to be used outside the setup
export function useClientStoreWithOut() {
    return useClientStore(store)
}
