using Knoks.Api.Entities;
using Knoks.Core.Entities;
using Knoks.Core.Entities.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace Knoks.Api.Filters
{
    public class ApiResponseResultFilter : Attribute, IResultFilter
    {
        public void OnResultExecuted(ResultExecutedContext context)
        {
        }

        public void OnResultExecuting(ResultExecutingContext context)
        {
            ObjectResult objectResult;
            objectResult = context.Result as ObjectResult;
            if (objectResult != null)
            {
                if (objectResult.Value is IApiResult)
                    context.Result = new OkObjectResult(new ApiResponse { Result = objectResult.Value });
                else
                    context.Result = new NotFoundObjectResult(new ApiResponse { Error = new ApiError(ApiErrorType.Undefined, "NotFoundObjectResult") });
            }
        }
    }
}
