using System;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Log;

namespace Siger.ApiCommon.Filters
{
    public class ModelValidateFilter: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var modelError = context.ModelState.FirstOrDefault();
                var error = modelError.Value.Errors.Select(e => e.ErrorMessage).FirstOrDefault();
                if (!string.IsNullOrEmpty(error))
                {
                    var result = Enum.TryParse(error, true, out RequestEnum requestError);
                    var message = result ? (Enum) requestError : CommonEnum.SystemExcetion;
                    Logger.WriteLineError($"OnActionExecuting:{error}");
                    var response = new ObjectResult(new ResultFilter.ResultObject(0, (int)Convert.ChangeType(message, typeof(int)), null));
                    context.Result = response;
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                }
            }
        }
    }
}
