using C4IT.DataHistoryProvider;
using C4IT.FASD.Base;
using C4IT.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using static C4IT.Logging.cLogManager;

namespace F4SDwebService.Controllers
{
    public class GetDetailsDataController : ApiController
    {
        public async Task<IHttpActionResult> Get(string jsonRequest)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            try
            {
                var Request = JsonConvert.DeserializeObject<cF4sdHealthCardRawDataRequest>(jsonRequest);
                var requestId = Request.Identities?.First()?.Id.ToString();
                var requestInfo = new cF4sdWebRequestInfo("GetDetailsData", requestId, cAuthentication.GetUserInfo(ActionContext));

                if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceStart(0, requestInfo.requestName, requestInfo.id, requestInfo.created); }

                var apiError = 0;

                try
                {
                    var RetVal = await WebApiApplication.Collector.GetDetailsTableResultsAsync(Request.Tables, Request.Identities, Request.RefTime, Request.MaxAge, CancellationToken.None, requestInfo, 1).ConfigureAwait(false);

                    if (RetVal != null)
                        return Ok(RetVal);

                    return Ok(new List<cF4SDHealthCardRawData.cHealthCardDetailsTable>());
                }
                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); }
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
            }

            return BadRequest();
        }
    }
}