import { isRegistered, register, unregister, unregisterAll } from '@tauri-apps/plugin-global-shortcut'

export default defineNuxtPlugin({
  async setup() {
    const { isTauri, toggleInput, toggleOutput } = useApp()
    const preferences = usePreferences()

    if (!isTauri.value)
      return

    await unregisterAll()

    watch(preferences.toggleInputHotkey, async (shortcut, prevShortcut) => {
      await registerHotkey(shortcut, prevShortcut, toggleInput)
    }, {
      immediate: true,
    })

    watch(preferences.toggleOutputHotkey, async (shortcut, prevShortcut) => {
      await registerHotkey(shortcut, prevShortcut, toggleOutput)
    }, {
      immediate: true,
    })

    async function registerHotkey(shortcut: string, prevShortcut: string | undefined, cb: () => void) {
      if (!!prevShortcut && await isRegistered(prevShortcut)) {
        await unregister(prevShortcut)
      }

      if (!shortcut)
        return

      if (await isRegistered(shortcut)) {
        await unregister(shortcut)
      }

      await register(shortcut, ({ state }) => {
        if (state !== 'Released')
          return

        cb()
      })
    }
  },
})
