import * as signalR from '@microsoft/signalr'
import type { KbxImportProgressEvent } from '@kbx/contracts'
import type { KbxImportProgressConnection } from '@kbx/ui'

export function createImportProgressConnection(url = '/hubs/import-progress'): KbxImportProgressConnection {
  const hub = new signalR.HubConnectionBuilder()
    .withUrl(url)
    .withAutomaticReconnect()
    .build()

  return {
    start: () => hub.state === signalR.HubConnectionState.Disconnected ? hub.start() : Promise.resolve(),
    stop: () => hub.stop(),
    subscribe: sessionId => hub.invoke('Subscribe', sessionId),
    unsubscribe: sessionId => hub.state === signalR.HubConnectionState.Connected
      ? hub.invoke('Unsubscribe', sessionId)
      : Promise.resolve(),
    onProgress(callback) {
      hub.on('ImportProgress', (event: KbxImportProgressEvent) => callback(event))
    },
  }
}
