import type { HubConnection } from '@microsoft/signalr'
import { HubConnectionBuilder } from '@microsoft/signalr'
import { useState, useEffect } from 'react'

import useApiUrlStore from '../app/store/apiStore'

export const useHub = () => {
  const { workerUrl } = useApiUrlStore()
  const [connectionRef, setConnection] = useState<HubConnection>()

  function createHubConnection() {
    const con = new HubConnectionBuilder()
      .withUrl(`${workerUrl}/positionhub`)
      .withAutomaticReconnect()
      .build()
    setConnection(con)
  }

  useEffect(() => {
    createHubConnection()
  }, [])

  useEffect(() => {
    if (connectionRef) {
      try {
        connectionRef.on('PositionsSubscription', (positions) => {
          console.log(positions)
        })

        connectionRef
          .start()
          .then((result) => {
            console.log(result)
          })
          .catch((err) => {
            console.error(`Error: ${err}`)
          })
      } catch (error) {
        console.error(error as Error)
      }
    }

    return () => {
      connectionRef
    }
  }, [connectionRef])
}
