using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using Performance.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Performance.Api
{
    public class ExceptionsFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<ExceptionsFilter> _logger;

        public ExceptionsFilter(ILogger<ExceptionsFilter> logger)
        {
            this._logger = logger;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.Exception is PerformanceException)
            {
                _logger.LogWarning($"接口错误警告:{context.Exception.ToString()}");
                var response = new ApiResponse(ResponseType.Fail, context.Exception.Message);
                context.Result = new ObjectResult(response);
                LogHelper.Warning(JsonHelper.Serialize(response), "接口错误警告");
            }
            else if (context.Exception is PerformanceTokenErrorException)
            {
                _logger.LogWarning($"Token Error:{context.Exception.ToString()}");
                var response = new ApiResponse(ResponseType.TokenError, context.Exception.Message);
                context.Result = new ObjectResult(response);
                LogHelper.Warning(JsonHelper.Serialize(response), "Token Error");
            }
            else
            {
                _logger.LogError($"接口异常:{context.Exception.ToString()}");
                var response = new ApiResponse(ResponseType.Error, "接口内部异常", context.Exception.Message);
                context.Result = new ObjectResult(response);
                LogHelper.Error(JsonHelper.Serialize(response), "接口内部异常");
            }
            return Task.CompletedTask;
        }
    }
}
