using EVCB_OCPP.WEBAPI.Helpers;
using EVCB_OCPP.WEBAPI.Models;
using EVCB_OCPP.WEBAPI.Models.WebAPI;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace EVCB_OCPP.WEBAPI.Handlers
{
    //public class APILogHandler : DelegatingHandler
    //{
    //    public class ApiLogHandler : DelegatingHandler
    //    {
    //        //   private NLog.ILogger logger = LogManager.GetCurrentClassLogger();
    //        private string apiLogConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["APILogDBContext"].ConnectionString;



    //        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    //        {
    //            string uri = request.RequestUri.ToString();

    //            var apiLogEntry = CreateApiLogEntryWithRequestData(request);

    //            if (request.Content != null)
    //            {
    //                await request.Content.ReadAsStringAsync()
    //                    .ContinueWith(task =>
    //                    {
    //                        apiLogEntry.RequestContentBody = task.Result;

    //                    }, cancellationToken);
    //            }


    //            return await base.SendAsync(request, cancellationToken)
    //                .ContinueWith(task =>
    //                {
    //                    if(request.RequestUri.AbsolutePath.Contains("api/v1/file"))
    //                    {                           
    //                        return task.Result;
    //                    }
                     
    //                    if(task.IsFaulted)
    //                    {
    //                        var result = new CPOOuterResponse() { StatusCode = (int)CPO_StatusCode.UnexpectedError, StatusMessage = CPO_StatusMessage.ERROR_MSG_Global_UNEXPECTEDERROR };

    //                        apiLogEntry.ResponseContentBody = JsonConvert.SerializeObject(result, EVCBConfiguration.JSONSERIALIZER_FORMAT);
    //                        apiLogEntry.ResponseContentType = "";
    //                        apiLogEntry.ResponseHeaders = "";

    //                        apiLogEntry.ErrorOn = DateTime.Now;
    //                        apiLogEntry.ErrorMsg = task.Exception.ToString().Replace("'", " ");

    //                        apiLogEntry.ResponseStatusCode = (int) HttpStatusCode.InternalServerError;
    //                        apiLogEntry.ResponseTimestamp = DateTime.Now;
    //                        WriteLog(apiLogEntry);
    //                        return request.CreateResponse(HttpStatusCode.InternalServerError, result);
    //                    }
    //                    else
    //                    {
    //                        var response = task.Result;

    //                        if (response.Content != null)
    //                        {
    //                            apiLogEntry.ResponseContentBody = response.Content.ReadAsStringAsync().Result;
    //                            apiLogEntry.ResponseContentType = response.Content.Headers.ContentType.MediaType;
    //                            apiLogEntry.ResponseHeaders = WebApiHelper.SerializeHeaders(response.Content.Headers);
    //                        }

    //                        int errorMessageIndex = apiLogEntry.ResponseContentBody.IndexOf(",\"ErrorDetail\"");
    //                        string endTag = apiLogEntry.ResponseContentBody.Last().ToString();

    //                        if (errorMessageIndex > 0)
    //                        {
    //                            string errorMsg = apiLogEntry.ResponseContentBody.Substring(errorMessageIndex).Remove(0, 16);
    //                            apiLogEntry.ResponseContentBody = apiLogEntry.ResponseContentBody.Remove(errorMessageIndex).Remove(0, 1);
    //                            apiLogEntry.ErrorOn = DateTime.Now;
    //                            apiLogEntry.ErrorMsg = errorMsg.Remove(errorMsg.Count() - 2).Replace("'", " ");

    //                            response = request.CreateResponse(response.StatusCode, JsonConvert.DeserializeObject("{" + apiLogEntry.ResponseContentBody + "}"));
    //                        }

    //                        apiLogEntry.ResponseStatusCode = (int)response.StatusCode;
    //                        apiLogEntry.ResponseTimestamp = DateTime.Now;
    //                        WriteLog(apiLogEntry);

    //                        return response;
    //                    }
                     
                            
    //                }, cancellationToken);
    //        }

    //        private ApiLogEntry CreateApiLogEntryWithRequestData(HttpRequestMessage request)
    //        {
    //            try
    //            {
    //                HttpContext context = (HttpContext)(request["MS_HttpContext"]);
    //                var routeData = request.GetRouteData();

    //                return new ApiLogEntry
    //                {
    //                    Application = "[Api]",
    //                    User = context.User.Identity.Name,
    //                    Machine = Environment.MachineName,
    //                    RequestContentType = context.Request.ContentType,
    //                    RequestRouteTemplate = routeData.Route.RouteTemplate,
    //                    RequestRouteData = "",
    //                    RequestIpAddress = context.Request.UserHostAddress,
    //                    RequestMethod = request.Method.Method,
    //                    RequestHeaders = WebApiHelper.SerializeHeaders(request.Headers),
    //                    RequestTimestamp = DateTime.Now,
    //                    RequestUri = request.RequestUri.ToString()
    //                };
    //            }
    //            catch (Exception ex)
    //            {
    //                //  logger.Debug(" " + ex.ToString());
    //                return null;
    //            }

    //        }

    //        private ApiLogEntry CreateApiLogEntryWithRequestData_Temp(HttpRequestMessage request)
    //        {
    //            try
    //            {
    //                HttpContext context = ((HttpContext)request["MS_HttpContext"]);
    //                var routeData = request.GetRouteData();

    //                return new ApiLogEntry
    //                {
    //                    Application = "[Api]",
    //                    User = context.User.Identity.Name,
    //                    Machine = Environment.MachineName,
    //                    RequestContentType = context.Request.ContentType,
    //                    RequestRouteTemplate = routeData.Route.RouteTemplate,
    //                    RequestIpAddress = context.Request.UserHostAddress,
    //                    RequestMethod = request.Method.Method,
    //                    RequestHeaders = WebApiHelper.SerializeHeaders(request.Headers),
    //                    RequestTimestamp = DateTime.Now,
    //                    RequestUri = request.RequestUri.ToString()
    //                };
    //            }
    //            catch (Exception ex)
    //            {
    //                // logger.Debug("11111 " + ex.ToString());
    //                return null;
    //            }

    //        }

    //        private void WriteLog(ApiLogEntry log)
    //        {
    //            try
    //            {

    //                if (log == null) return;
    //                using (var conn = new SqlConnection(apiLogConnectionString))
    //                {
    //                    conn.Open();

    //                    using (var cmd = new SqlCommand("[dbo].[uspInsertApiLog]", conn))
    //                    {

    //                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
    //                        cmd.Parameters.Add(new SqlParameter("Application", log.Application));
    //                        cmd.Parameters.Add(new SqlParameter("User", log.User));
    //                        cmd.Parameters.Add(new SqlParameter("Machine", log.Machine));
    //                        cmd.Parameters.Add(new SqlParameter("RequestIpAddress", log.RequestIpAddress));
    //                        cmd.Parameters.Add(new SqlParameter("RequestContentType", log.RequestContentType));
    //                        cmd.Parameters.Add(new SqlParameter("RequestUri", log.RequestUri));
    //                        cmd.Parameters.Add(new SqlParameter("RequestMethod", log.RequestMethod));
    //                        cmd.Parameters.Add(new SqlParameter("RequestRouteTemplate", log.RequestRouteTemplate));
    //                        cmd.Parameters.Add(new SqlParameter("RequestRouteData", ""));//log.RequestRouteData
    //                        cmd.Parameters.Add(new SqlParameter("RequestHeaders", log.RequestHeaders));
    //                        cmd.Parameters.Add(new SqlParameter("RequestTimestamp", log.RequestTimestamp));

    //                        cmd.Parameters.Add(new SqlParameter("ResponseContentType", log.ResponseContentType));
    //                        cmd.Parameters.Add(new SqlParameter("ResponseStatusCode", log.ResponseStatusCode));
    //                        cmd.Parameters.Add(new SqlParameter("ResponseHeaders", log.ResponseHeaders));
    //                        cmd.Parameters.Add(new SqlParameter("ResponseTimestamp", log.ResponseTimestamp));

    //                        cmd.Parameters.Add(new SqlParameter("IsOutData", log.IsOutData));
    //                        cmd.Parameters.Add(new SqlParameter("ErrorMsg", log.ErrorMsg));
    //                        cmd.Parameters.Add(new SqlParameter("ErrorOn", log.ErrorOn));
    //                        cmd.Parameters.Add(new SqlParameter("RequestContentBody", log.RequestContentBody));
    //                        cmd.Parameters.Add(new SqlParameter("ResponseContentBody", log.ResponseContentBody));

    //                        cmd.ExecuteNonQuery();
    //                    }
    //                }


    //            }
    //            catch (Exception ex)
    //            {
    //                Console.WriteLine(ex.ToString());
    //            }


    //        }
    //    }
    //}
}