/**
 * 事件监听 Hook
 */

import { onMounted, onUnmounted } from 'vue'
import { listen } from '@tauri-apps/api/event'

/**
 * 监听 Tauri 事件
 * @param {string} eventName 事件名称
 * @param {Function} handler 事件处理器
 */
export function useEventListener(eventName, handler) {
  let unlisten = null

  onMounted(async () => {
    unlisten = await listen(eventName, (event) => {
      handler(event.payload)
    })
  })

  onUnmounted(() => {
    unlisten?.()
  })
}

/**
 * 监听多个事件
 * @param {Array<{name: string, handler: Function}>} events 事件配置数组
 */
export function useMultipleEventListeners(events) {
  const unlisteners = []

  onMounted(async () => {
    for (const event of events) {
      const unlisten = await listen(event.name, (e) => {
        event.handler(e.payload)
      })
      unlisteners.push(unlisten)
    }
  })

  onUnmounted(() => {
    unlisteners.forEach(fn => fn())
  })
}
