using Knoks.Api.Controllers.Base;
using Knoks.Api.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;

namespace Knoks.Api.Constraints
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger _logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            ApiError error = (context.Exception as ApiResponseException)?.Error;
            var validation = context.Exception as Knoks.Core.Logic.Interfaces.IValidationException;
            if (error == null && validation != null) {
                error = new ApiError(ApiErrorType.Validation, validation.Message, validation.Errors);
            }
            if (error == null)
            {
                _logger.LogError(new EventId(), context.Exception, "GlobalExceptionFilter");

                var msg = context.Exception.Message + Environment.NewLine + context.Exception.StackTrace;
                error = new ApiError(ApiErrorType.Undefined, msg);
            }
            context.Result = new OkObjectResult(new ApiResponse { Error = error });
        }
    }
}
