using C4IT.DataHistoryProvider.Base.DataSources;
using C4IT.FASD.Base;
using C4IT.FASD.Communication.Agent;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace C4IT.DataHistoryProvider.Base.Modules.Agent
{
    public class AgentRemoteDesktopManager : IRemoteDesktopManager<AgentRemoteConnectionInfo, AgentRemoteClientInfo, AgentRemoteConnectionStatusDto>
    {
        private readonly AgentApiHandler _agentApiHandler;

        public AgentRemoteDesktopManager(cAgentApiConfiguration agentConfig)
        {
            _agentApiHandler = new AgentApiHandler(agentConfig);
        }

        public async Task<AgentRemoteConnectionStatusDto> GetConnectionStatus(Guid connectionId)
        {
            return await _agentApiHandler.Request<AgentRemoteConnectionStatusDto>($"api/management/c4it/phoenix-connections/{connectionId}/status", HTTP.eHttpMethod.get);
        }

        public async Task<AgentRemoteConnectionInfo> InitiateConnectionOfClient(AgentRemoteClientInfo clientInfos, bool isElevated, CancellationToken token)
        {
            string url = "api/management/c4it/phoenix-connections";
            if (isElevated)
                url += "/admin";

            return await _agentApiHandler.Request<AgentRemoteConnectionInfo>(url, HTTP.eHttpMethod.post, clientInfos, token);
        }

        public async Task TerminateConnection(Guid connectionId)
        {
            await _agentApiHandler.Request($"api/management/c4it/phoenix-connections/{connectionId}", HTTP.eHttpMethod.delete);
        }

        public bool IsActive() => true;

        public Task<HealthInformation> GetHealthInfo()
        {
            // todo Agent Server has to implement an "health" endpoint and return its result
            return Task.FromResult(new HealthInformation(HealthStatus.healthy));
        }
    }
}
