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(ValidationErrorType.NotChangeable, Property);
                        IsValid = false;
                    }
                }

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

            if (objectPatch.Operations.Any(m => m.path == "/ownerid"))
            {
                biz.AddError(ValidationErrorType.NotChangeable, "OwnerId");
                IsValid = false;
            }

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

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

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

            return IsValid;
        }



    }//eoc

}//eons