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);
                _logger.LogWarning("接口错误警告" + 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);
                _logger.LogWarning("Token Error" + JsonHelper.Serialize(response));
            }
            else
            {
                _logger.LogError($"接口异常:{context.Exception}");
                var response = new ApiResponse(ResponseType.Error, "服务器繁忙，请稍后再试...", context.Exception.Message);
                context.Result = new ObjectResult(response);
                _logger.LogError("接口内部异常" + JsonHelper.Serialize(response));
            }
            return Task.CompletedTask;
        }
    }
}
