import { defineStore } from 'pinia'
import type { Connection } from '../composables/useData'
import { useConnection } from '../composables/useData'

export interface State {
  connections: ConnectionState[]
}
export interface ConnectionState {
  id: string
  content: string
}
export interface CurrentConnection extends Connection {
  active: boolean
  content: string
}

export const useConnectionStore = defineStore('connection', () => {
  const { connections: rawConnections } = useConnection()

  const connections = ref<ConnectionState[]>([])

  const currentConnections = ref<CurrentConnection[]>([])

  const activeConnections = computed(() => {
    return currentConnections.value.filter(item => item.active) || []
  })
  watch(
    rawConnections,
    () => {
      setConnections(connections.value)
    },
    { once: true }
  )

  watch(
    currentConnections,
    () => {
      connections.value = currentConnections.value
        .filter(item => item.active)
        .map(item => {
          return { id: item.id, content: item.content }
        })
    },
    { immediate: true, deep: true }
  )

  function setConnections(list: ConnectionState[]) {
    connections.value = list
    if (rawConnections.value.length === 0) return
    currentConnections.value = rawConnections.value.map(item => {
      const found = list?.find(({ id }) => id === item.id)
      return found ? { ...item, active: true, content: found.content } : { ...item, active: false, content: '' }
    })
  }

  function setData(data: State) {
    if (!data?.connections) return
    setConnections(data.connections)
  }

  return { connections, currentConnections, activeConnections, rawConnections, setConnections, setData }
})
