using AipGateway.API.Service.Controllers;
using AipGateway.Data;
using AipGateway.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security;

namespace AipGateway.API.Service.Filters
{
    public class AipApiAsyncActionFilter : IAsyncActionFilter
    {
        private readonly ILogger _logger;
        private readonly AipDbContext _aipDb = null;

        public AipApiAsyncActionFilter(ILogger<AipApiAsyncActionFilter> logger, AipDbContext aipDb)
        {
            _logger = logger;
            _aipDb = aipDb;
            _logger.LogError("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: AipApiAsyncActionFilter");
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            long startTicks = DateTime.UtcNow.Ticks;
            string apiPath = context.HttpContext.Request.Path;
            DateTime StartedAt = DateTime.UtcNow;
            //_logger.LogError("OnActionExecutionAsync Before: {0}", context.ToString());
            //if (context.Controller.GetType() == typeof(AipFileController))
            //{
            //    AipFileController aipFileController = (AipFileController)context.Controller;
            //    _logger.LogError("OnActionExecutionAsync aipFileController: {0}", context.HttpContext.Request.Path);
            //    var apiKey = context.HttpContext.Request.Query["apiKey"];
            //    if (apiKey[0] != null)
            //    {
            //        _logger.LogError("OnActionExecutionAsync apiKey: {0}", apiKey[0]);
            //    }
            //}

            await next();

            //long endTicks = DateTime.UtcNow.Ticks;
            //long elapsedTicks = DateTime.UtcNow.Ticks - startTicks;
            TimeSpan elapsedSpan = new TimeSpan(DateTime.UtcNow.Ticks - startTicks);
            _logger.LogError("OnActionExecutionAsync: {0}, : {1} ms", apiPath, elapsedSpan.TotalMilliseconds);

            TbAipApiCallLog callLog = new TbAipApiCallLog
            {
                Id = 1,
                LogDate = DateTime.UtcNow,
                ApiId = 1,
                ApiGuid = apiPath,
                StartedAt = StartedAt,
                CompletedAt = DateTime.UtcNow,
                CallIpAddr = context.HttpContext?.Connection?.RemoteIpAddress?.ToString(),
                CallResult = "0",
                CallMessage = "Success",
            };
            _aipDb.AipApiCallLogs.Add(callLog);
            _aipDb.SaveChanges();

            //long userId = 1;
            // long organizationId = context.HttpContext.GetTenantIdentifier();
            //long organizationId = 1;

            //if (await _roleVerificationRepository.VerifyUser(userId, organizationId, _permission) == false)
            //{
            //    context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
            //    return;
            //}
            //await next();
        }
    }
}
