using Microsoft.AspNetCore.SignalR.Client;
using RTCommunicatorBase;
using System.Threading.Tasks;

namespace RTCommunicatorSingalR;

public class RTCommunicator_SingalR : IRTMini8Sender
{
    private HubConnection _hubConnection;
    private IRTMini8Provider _provider;
    private string _ipAddress;
    private int _port; 

    bool IRTMini8Sender.Initialize(IRTMini8Provider provider)
    {
        if (provider is null)
            return false;

        if (this._provider is not null)
            return false;

        this._provider = provider;
        return true;
    }
    bool IRTMini8Sender.StartService(string ip, int port)
    {
        if (_provider is null)
            return false;

        if (this._hubConnection is not null)
            return false;

        if (string.IsNullOrEmpty(ip) || port < 5000 || port > ushort.MaxValue)
            return false;

        HubConnection tempHub = new HubConnectionBuilder().WithUrl($"http://{ip}:{port}/RTHub").WithAutomaticReconnect().Build();

        this._ipAddress = ip;
        this._port = port;

        //注册断线及重连事件
        tempHub.Closed += Hub_Closed; ;
        tempHub.Reconnected += Hub_Reconnected;
        tempHub.Reconnecting += Hub_Reconnecting;

        try
        {
            tempHub.StartAsync().Wait();
            this._provider?.Connected(this._ipAddress, this._port);
        }
        catch
        {
            return false;
        }
        this._hubConnection = tempHub;

        return true;
    }

    bool IRTMini8Sender.SelectConfigFile(string name)
    {
        try
        {
            return this._hubConnection.InvokeAsync<bool>("SelectConfigFile", name).Result;
        }
        catch
        {
            return false;
        }
    }

    bool IRTMini8Sender.CloseService()
    {
        this._hubConnection?.DisposeAsync();
        this._hubConnection = null;
        this._provider = null;
        return true;
    }


    private Task Hub_Reconnecting(System.Exception arg)
    {
        this._provider?.DisConnected(this._ipAddress, this._port);
        return Task.CompletedTask;
    }

    private Task Hub_Reconnected(string arg)
    {
        this._provider?.Connected(this._ipAddress, this._port);
        return Task.CompletedTask;
    }

    private Task Hub_Closed(System.Exception arg)
    {
        this._provider?.DisConnected(this._ipAddress, this._port);
        return Task.CompletedTask;
    }
}
