using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using AyaNova.Biz;

namespace AyaNova.Api.ControllerHelpers
{



    public class ApiErrorResponse
    {

        [JsonIgnore]
        private ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger<ApiErrorResponse>();

        //Mandatory properties
        public ApiError Error { get; }




        //Generic error
        public ApiErrorResponse(ApiErrorCode apiCode, string target = null, string message = null)
        {

            //try to get a stock message if nothing specified
            if (message == null)
            {
                message = ApiErrorCodeStockMessage.GetMessage(apiCode);
            }

            Error = new ApiError(apiCode, message, target);

            log.LogDebug("apiCode={0}, target={1}, message={2}", apiCode, target, message);
        }


        //Bad request (MODELSTATE ISSUE) error response handling

        public ApiErrorResponse(ModelStateDictionary modelState)
        {

            if (modelState.IsValid)
            {
                throw new ArgumentException("ModelState must be invalid", nameof(modelState));
            }


            //Set outer error and then put validation in details

            Error = new ApiError(ApiErrorCode.VALIDATION_FAILED, ApiErrorCodeStockMessage.GetMessage(ApiErrorCode.VALIDATION_FAILED));


            //https://www.jerriepelser.com/blog/validation-response-aspnet-core-webapi/
            //Message = "Validation Failed";
            Error.Details = new List<ApiDetailError>();

         
            foreach (var key in modelState.Keys)
            {
                var vErrors = modelState[key].Errors;
                foreach (ModelError m in vErrors)
                {
                    string msg = "";
                    if (!string.IsNullOrWhiteSpace(m.ErrorMessage))
                    {
                        msg += m.ErrorMessage + ". ";
                    }
                    if (m.Exception != null && !string.IsNullOrWhiteSpace(m.Exception.Message))
                    {
                        msg += "Exception: " + m.Exception.Message;
                    }
                    //example this produces
                    //
                    Error.Details.Add(new ApiDetailError() { Target = key, Message = msg, Error = ((int)ApiErrorCode.VALIDATION_INVALID_VALUE).ToString() });
                }
            }


            log.LogDebug("BadRequest - Validation error");
        }


        //Business rule validation error response
        public ApiErrorResponse(List<ValidationError> errors)
        {
            Error = new ApiError(ApiErrorCode.VALIDATION_FAILED, ApiErrorCodeStockMessage.GetMessage(ApiErrorCode.VALIDATION_FAILED));
            Error.Details = new List<ApiDetailError>();
            foreach (ValidationError v in errors)
            {
                Error.Details.Add(new ApiDetailError() { Target = v.Target, Message = v.Message, Error = ((int)v.Code).ToString() });
            }
            log.LogDebug("BadRequest - Validation error");
        }



        // public void AddDetailError(ApiErrorCode apiCode, string target = null, string message = null)
        // {
        //     if (Error.Details == null)
        //     {
        //         Error.Details = new List<ApiDetailError>();
        //     }

        //     //try to get a stock message if nothing specified
        //     if (message == null)
        //     {
        //         message = ApiErrorCodeStockMessage.GetMessage(apiCode);
        //     }

        //     Error.Details.Add(new ApiDetailError() { Code = ((int)apiCode).ToString(), Target = target, Message = message });
        // }


    }//eoc


}//eons