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

namespace FasdWebService.Controllers
{
    [RoutePrefix("api/Ticketing")]
    public class TicketingController : ApiController
    {
        [HttpGet]
        [Route("GetExternalLink")]
        public async Task<IHttpActionResult> GetExternalLink(Guid ticketId, enumTicketExternalOpenMode mode)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            var requestInfo = new cF4sdWebRequestInfo("Ticketing.GetExternalLink", ticketId.ToString(), cAuthentication.GetUserInfo(ActionContext));
            if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceStart(0, requestInfo.requestName, requestInfo.id, requestInfo.created); }

            var apiError = 0;
            try
            {
                if (ticketId == Guid.Empty || mode == enumTicketExternalOpenMode.None)
                    return BadRequest();

                var result = await WebApiApplication.Collector.GetTicketExternalLinkAsync(ticketId, mode, requestInfo, 1, CancellationToken.None);
                return Ok(result ?? new cTicketExternalLinkResult
                {
                    Success = false,
                    Mode = enumTicketExternalOpenMode.None
                });
            }
            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 Ok(new cTicketExternalLinkResult
            {
                Success = false,
                Mode = enumTicketExternalOpenMode.None
            });
        }
    }
}
