using LHDN.CRM.BC.Repositories;
using LHDN.CRM.Models.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace LHDN.CRM.WebAPI.Handlers
{
    public class PerfLogHandler : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var log = new PerfLog()
            {
                RequestUri = request.RequestUri.AbsoluteUri,
                StartTime = DateTime.Now
            };

            var response = await base.SendAsync(request, cancellationToken);

            await SendToPerfLog(log);
            return response;
        }

        private async Task<bool> SendToPerfLog(PerfLog entity)
        {
            entity.EndTime = DateTime.Now;
            entity.Duration = Convert.ToDecimal((entity.EndTime - entity.StartTime).TotalMilliseconds / 1000);

            await Task.Run(() => {

                using (PerfLogRepository repo = new PerfLogRepository())
                {
                    repo.Log(entity);
                }
            });

            return true;
        }
    }
}