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

namespace F4SDwebService.Controllers
{
    public class RemoteDesktopController : ApiController
    {
        private readonly IRemoteDesktopManager<AgentRemoteConnectionInfo, AgentRemoteClientInfo, AgentRemoteConnectionStatusDto> _remoteDesktopManager;

        public RemoteDesktopController()
        {
            var agentConfig = WebApiApplication.Collector.F4sdAgent.GetAgentApiConfiguration(true);
            _remoteDesktopManager = new AgentRemoteDesktopManager(agentConfig);
        }

        [HttpPost]
        [Route("api/RemoteDesktop/Initiate")]
        public async Task<IHttpActionResult> Initiate([FromBody] AgentRemoteClientInfo clientInfo, [FromUri] bool isElevated, CancellationToken token = default)
        {
            AgentRemoteConnectionInfo connection = await _remoteDesktopManager.InitiateConnectionOfClient(clientInfo, isElevated, token);

            if (connection is null)
                return NotFound();
            else if (connection.Errors is null)
                return Ok(connection);
            else
                return Content(System.Net.HttpStatusCode.BadRequest, connection);
        }

        [HttpGet]
        [Route("api/RemoteDesktop/{connectionId}/Status")]
        public async Task<IHttpActionResult> GetStatus(Guid connectionId)
        {
            AgentRemoteConnectionStatusDto status = await _remoteDesktopManager.GetConnectionStatus(connectionId);

            if (status is null)
                return NotFound();

            return Ok(status);
        }

        [HttpDelete]
        [Route("api/RemoteDesktop/{connectionId}/Stop")]
        public async Task<IHttpActionResult> Stop(Guid connectionId)
        {
            await _remoteDesktopManager.TerminateConnection(connectionId);
            return Ok();
        }

        [HttpGet]
        [Route("api/RemoteDesktop/IsActive")]
        public IHttpActionResult IsActive()
        {
            bool isActive = _remoteDesktopManager.IsActive();
            return Ok(isActive);
        }

        [HttpGet]
        [Route("api/RemoteDesktop/health")]
        public async Task<IHttpActionResult> GetHealth()
        {
            HealthInformation healthInfo = await _remoteDesktopManager.GetHealthInfo();
            return Ok(healthInfo);
        }
    }
}