import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getAllCADDefinitions, getDisplayableCADs } from '@/config/cad'


export const useCADStore = defineStore('cad', () => {
  // 从配置生成CAD软件连接状态
  const initializeCADConnections = () => {
    const cadDefinitions = getAllCADDefinitions()
    return cadDefinitions.map(cad => ({
      id: cad.id,
      name: cad.displayName,
      fullName: cad.name,
      icon: cad.icon,
      version: cad.version,
      port: cad.port,
      description: cad.description,
      features: cad.features,
      priority: cad.priority,
      connected: false,
      connecting: false,
      lastConnected: null
    }))
  }

  // CAD软件连接状态 - 配置驱动
  const cadConnections = ref(initializeCADConnections())

  // 当前项目名称
  const currentProjectName = ref(null)

  // 当前连接的CAD软件
  const currentCAD = computed(() => {
    return cadConnections.value.find(cad => cad.connected)
  })


  // 获取可显示的CAD列表（根据显示模式）
  const displayableCADs = computed(() => {
    return getDisplayableCADs()
  })


  // 获取CAD连接状态（通过名称或ID）
  const getCADConnection = (identifier) => {
    return cadConnections.value.find(cad =>
      cad.name === identifier ||
      cad.id === identifier ||
      cad.fullName === identifier
    )
  }

  // 检查CAD是否支持特定功能
  const cadSupportsFeature = (cadId, feature) => {
    const cad = getCADConnection(cadId)
    return cad ? cad.features.includes(feature) : false
  }

  // 设置CAD连接状态（一次只能连接一个）
  const setCADConnection = (cadName, connected) => {
    // 先断开所有连接
    cadConnections.value.forEach(cad => {
      cad.connected = false
      cad.connecting = false
      if (!connected) {
        cad.lastConnected = null
      }
    })

    // 设置指定CAD的连接状态
    const targetCAD = getCADConnection(cadName)
    if (targetCAD) {
      targetCAD.connected = connected
      if (connected) {
        targetCAD.lastConnected = new Date()
      }
    }
  }

  // 设置CAD连接中状态
  const setCADConnecting = (cadName, connecting) => {
    const cad = getCADConnection(cadName)
    if (cad) {
      cad.connecting = connecting
    }
  }

  // 设置当前项目名称
  const setCurrentProjectName = (projectName) => {
    currentProjectName.value = projectName
  }


  return {
    // 状态
    cadConnections,
    currentCAD,
    currentProjectName,
    displayableCADs,

    // 方法
    getCADConnection,
    cadSupportsFeature,
    setCADConnection,
    setCADConnecting,
    setCurrentProjectName
  }
})