using System;
using System.Threading.Tasks;
using FarmmapsApi.Models;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Logging;

namespace FarmmapsApi.Services
{
    public class FarmmapsEventHub
    {
        private readonly Configuration _configuration;
        private readonly HttpClientSettings _httpClientSettings;

        private HubConnection _hubConnection;

        public event Action<EventMessage> EventCallback;

        public FarmmapsEventHub(HttpClientSettings httpClientSettings, Configuration configuration)
        {
            _httpClientSettings = httpClientSettings;
            _configuration = configuration;
        }
        
        public async Task StartEventHub()
        {
            if(_hubConnection != null)
                throw new Exception("EventHub already started");
            
            var eventEndpoint = $"{_configuration.Endpoint}/EventHub";
            _hubConnection = new HubConnectionBuilder()
                .WithUrl(eventEndpoint, HttpTransportType.WebSockets,
                    options => options.SkipNegotiation = true)
                .ConfigureLogging(log => log.AddConsole())
                .WithAutomaticReconnect()
                .Build();

            await _hubConnection.StartAsync();
            await _hubConnection.SendAsync("authenticate", _httpClientSettings.BearerToken);

            _hubConnection.Reconnected += async s => await _hubConnection.SendAsync("authenticate", _httpClientSettings.BearerToken);
            _hubConnection.On("Event", (EventMessage eventMessage) => EventCallback?.Invoke(eventMessage));
        }
    }
}