import { computed, ref } from 'vue'
import { defineStore } from 'pinia'

type PipeLogLevel = 'info' | 'success' | 'warning' | 'error'
type PipeLogCategory = 'connection' | 'auth' | 'message'
type PipeLogDirection = 'system' | 'recv' | 'send'

type PipeRendererEvent = {
  timestamp: string
  level: PipeLogLevel
  category: PipeLogCategory
  direction: PipeLogDirection
  message: string
  detail?: string
  msgId?: number
  msgName?: string
  payloadLength?: number
  payloadHex?: string
  payloadText?: string
  connected: boolean
  authenticated: boolean
}

export type PipeLogEntry = PipeRendererEvent & {
  id: number
}

const MAX_LOG_COUNT = 500

export const usePipeStore = defineStore('pipe', () => {
  const logs = ref<PipeLogEntry[]>([])
  const connected = ref(false)
  const authenticated = ref(false)
  const lastEventAt = ref('')
  const seed = ref(0)

  const statusText = computed(() => {
    if (authenticated.value) return 'Authenticated'
    if (connected.value) return 'Connected / Waiting Auth'
    return 'Disconnected'
  })

  function append(event: PipeRendererEvent) {
    connected.value = event.connected
    authenticated.value = event.authenticated
    lastEventAt.value = event.timestamp
    seed.value += 1

    logs.value.push({
      id: seed.value,
      ...event
    })

    if (logs.value.length > MAX_LOG_COUNT) {
      logs.value.splice(0, logs.value.length - MAX_LOG_COUNT)
    }
  }

  function clear() {
    logs.value = []
  }

  return {
    logs,
    connected,
    authenticated,
    lastEventAt,
    statusText,
    append,
    clear
  }
})
