/**
 * 设备状态管理
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { discoveryApi, websocketApi, fileApi, configApi } from '@/api'

export const useDeviceStore = defineStore('device', () => {
  // 状态
  const devices = ref(new Map())
  const knownDevices = ref(new Map())  // 历史设备（包含离线设备）
  const localDevice = ref(null)
  const config = ref(null)
  const isDiscovering = ref(false)
  const isServerRunning = ref(false)
  const connectedDevices = ref(new Set())

  // 计算属性
  const deviceList = computed(() => Array.from(devices.value.values()))
  const onlineDevices = computed(() => deviceList.value.filter(d => d.online))
  const deviceCount = computed(() => devices.value.size)
  
  // 历史设备列表（排除在线设备，避免重复）
  const offlineKnownDevices = computed(() => {
    const result = []
    knownDevices.value.forEach((device, id) => {
      // 只显示不在在线列表中的设备
      if (!devices.value.has(id)) {
        result.push({ ...device, online: false })
      }
    })
    return result
  })

  // 初始化
  async function initialize() {
    try {
      // 获取本机设备信息
      localDevice.value = await configApi.getLocalDevice()
      
      // 获取配置
      config.value = await configApi.get()

      // 加载历史设备（用于显示离线设备的聊天记录）
      await loadKnownDevices()

      // 启动服务
      await startServices()
    } catch (error) {
      console.error('Failed to initialize device store:', error)
    }
  }

  // 启动所有服务
  async function startServices() {
    try {
      // 启动 HTTP 服务
      await fileApi.startServer()
      
      // 启动 WebSocket 服务
      await websocketApi.startServer()
      isServerRunning.value = true

      // 启动设备发现
      await discoveryApi.start()
      isDiscovering.value = true

      // 获取已发现的设备
      const existingDevices = await discoveryApi.getDevices()
      existingDevices.forEach(device => {
        devices.value.set(device.deviceId, device)
      })
    } catch (error) {
      console.error('Failed to start services:', error)
    }
  }

  // 停止所有服务
  async function stopServices() {
    try {
      await discoveryApi.stop()
      isDiscovering.value = false

      await websocketApi.stopServer()
      await fileApi.stopServer()
      isServerRunning.value = false

      devices.value.clear()
      connectedDevices.value.clear()
    } catch (error) {
      console.error('Failed to stop services:', error)
    }
  }

  // 添加设备
  function addDevice(device) {
    devices.value.set(device.deviceId, device)
    // 同时更新到已知设备
    knownDevices.value.set(device.deviceId, device)
  }

  // 移除设备
  function removeDevice(deviceId) {
    devices.value.delete(deviceId)
    connectedDevices.value.delete(deviceId)
    // 注意：不从 knownDevices 中删除，保留历史记录
  }

  // 获取设备（优先从在线设备获取，否则从历史设备获取）
  function getDevice(deviceId) {
    return devices.value.get(deviceId) || knownDevices.value.get(deviceId)
  }

  // 加载历史设备
  async function loadKnownDevices() {
    try {
      const devices = await discoveryApi.getKnownDevices()
      devices.forEach(device => {
        knownDevices.value.set(device.deviceId, device)
      })
    } catch (error) {
      console.error('Failed to load known devices:', error)
    }
  }

  // 设置设备连接状态
  function setDeviceConnected(deviceId, connected) {
    if (connected) {
      connectedDevices.value.add(deviceId)
    } else {
      connectedDevices.value.delete(deviceId)
    }

    const device = devices.value.get(deviceId)
    if (device) {
      device.online = connected
    }
  }

  // 检查设备是否已连接
  function isConnected(deviceId) {
    return connectedDevices.value.has(deviceId)
  }

  // 连接到设备
  async function connectToDevice(deviceId) {
    try {
      await websocketApi.connect(deviceId)
      setDeviceConnected(deviceId, true)
    } catch (error) {
      console.error('Failed to connect to device:', error)
      throw error
    }
  }

  // 断开设备连接
  async function disconnectFromDevice(deviceId) {
    try {
      await websocketApi.disconnect(deviceId)
      setDeviceConnected(deviceId, false)
    } catch (error) {
      console.error('Failed to disconnect from device:', error)
    }
  }

  // 更新设备名称
  async function updateDeviceName(name) {
    await configApi.updateDeviceName(name)
    if (localDevice.value) {
      localDevice.value.deviceName = name
    }
    if (config.value) {
      config.value.deviceName = name
    }
  }

  // 更新下载目录
  async function updateDownloadDir(dir) {
    await configApi.updateDownloadDir(dir)
    if (config.value) {
      config.value.downloadDir = dir
    }
  }

  return {
    // 状态
    devices,
    knownDevices,
    localDevice,
    config,
    isDiscovering,
    isServerRunning,
    connectedDevices,
    // 计算属性
    deviceList,
    onlineDevices,
    offlineKnownDevices,
    deviceCount,
    // 方法
    initialize,
    startServices,
    stopServices,
    addDevice,
    removeDevice,
    getDevice,
    loadKnownDevices,
    setDeviceConnected,
    isConnected,
    connectToDevice,
    disconnectFromDevice,
    updateDeviceName,
    updateDownloadDir,
  }
})
