using System.Linq;
using Microsoft.AspNetCore.JsonPatch;
using System;

namespace AyaNova.Biz
{


    internal static class ValidateJsonPatch<T> where T : class
    {

        internal static bool Validate(BizObject biz, JsonPatchDocument<T> objectPatch, string protectedProperties = "")
        {
            bool IsValid = true;

            string[] ProtectedProperties = null;
            if (!string.IsNullOrEmpty(protectedProperties))
            {
                protectedProperties = protectedProperties.Replace(", ", ",").Replace(" ,", ",").Trim();
                ProtectedProperties = protectedProperties.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }

            if (ProtectedProperties != null)
                foreach (string Property in ProtectedProperties)
                {
                    if (objectPatch.Operations.Any(m => m.path == $"/{Property.ToLowerInvariant()}"))
                    {
                        biz.AddError(ApiErrorCode.VALIDATION_NOT_CHANGEABLE, Property);
                        IsValid = false;
                    }
                }

            //check for in-valid patches
            if (objectPatch.Operations.Any(m => m.path == "/id"))
            {
                biz.AddError(ApiErrorCode.VALIDATION_NOT_CHANGEABLE, "Id");
                IsValid = false;
            }

     
            if (objectPatch.Operations.Any(m => m.path == "/serial"))
            {
                biz.AddError(ApiErrorCode.VALIDATION_NOT_CHANGEABLE, "Serial");
                IsValid = false;
            }

            if (objectPatch.Operations.Any(m => m.op == "add"))
            {
                biz.AddError(ApiErrorCode.INVALID_OPERATION, "add");
                IsValid = false;
            }

            if (objectPatch.Operations.Any(m => m.op == "remove"))
            {
                biz.AddError(ApiErrorCode.INVALID_OPERATION, "remove");
                IsValid = false;
            }

            return IsValid;
        }



    }//eoc

}//eons