using C4IT.DataHistoryProvider;
using C4IT.FASD.Base;
using C4IT.Logging;
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using static C4IT.Logging.cLogManager;


namespace F4SDwebService.Controllers.Matrix42
{
    public class Matrix42TicketFinalizationController : ApiController
    {
        [HttpPost]
        [Route("api/Matrix42/TicketFinalization")]
        public async Task<IHttpActionResult> Matrix42TicketFinalization([FromBody] cApiM42Ticket jsonRequest)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }
            var requestInfo = new cF4sdWebRequestInfo("Matrix42TicketFinalization", jsonRequest?.Action?.ToString() + " + " + jsonRequest?.Ticket?.ToString() ?? "", cAuthentication.GetUserInfo(ActionContext));
            if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceStart(0, requestInfo.requestName, requestInfo.id, requestInfo.created); }
            var apiError = 0;

            try
            {
                if (jsonRequest == null)
                    return BadRequest();

                if (string.Equals(jsonRequest.StatusIdValue, "Closed", StringComparison.InvariantCultureIgnoreCase))
                    await WebApiApplication.Collector.M42WpmCollector.ReopenM42TicketAsync(jsonRequest, requestInfo, 1, CancellationToken.None);

                string operationResult = null;
                switch (jsonRequest.Action)
                {
                    case enumCloseCaseTicketStatus.Save:
                        if (jsonRequest.Ticket == null || jsonRequest.Ticket.HasValue && jsonRequest.Ticket.Equals(Guid.Empty))
                            operationResult = await WebApiApplication.Collector.M42WpmCollector.CreateM42TicketAsync(jsonRequest, requestInfo, 1, CancellationToken.None);
                        else
                            operationResult = await WebApiApplication.Collector.M42WpmCollector.UpdateM42TicketAsync(jsonRequest, requestInfo, 1, CancellationToken.None);
                        break;
                    case enumCloseCaseTicketStatus.Close:
                        operationResult = await WebApiApplication.Collector.M42WpmCollector.CloseM42TicketAsync(jsonRequest, requestInfo, 1, CancellationToken.None);
                        break;
                    case enumCloseCaseTicketStatus.OnHold:
                        operationResult = await WebApiApplication.Collector.M42WpmCollector.PauseM42TicketAsync(jsonRequest, requestInfo, 1, CancellationToken.None);
                        break;
                    case enumCloseCaseTicketStatus.Forward:
                        operationResult = await WebApiApplication.Collector.M42WpmCollector.ForwardM42TicketAsync(jsonRequest, requestInfo, 1, CancellationToken.None);
                        break;
                    default:
                        return BadRequest();
                }

                if (operationResult == null)
                    return InternalServerError();

                var ticketId = jsonRequest.Ticket;
                if ((!ticketId.HasValue || ticketId.Value == Guid.Empty) && Guid.TryParse(operationResult, out var createdTicketId))
                    ticketId = createdTicketId;

                if (!ticketId.HasValue || ticketId.Value == Guid.Empty)
                    return InternalServerError();

                return Ok(new cTicketFinalizationResult
                {
                    Success = true,
                    TicketId = ticketId
                });
            }
            catch (Exception E)
            {
                apiError = E.HResult;
                LogException(E);
            }
            finally
            {
                if (WebApiApplication.Debug_apiTiming) WebApiApplication.SaveApiTimingEntry(requestInfo.requestName, requestInfo.id, requestInfo.created, apiError);
                if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceEnd(0, requestInfo.requestName, requestInfo.id, requestInfo.created, requestInfo.created, ErrorCode: apiError); }
                if (CM != null) LogMethodEnd(CM);
            }

            return BadRequest();
        }
    }
}
