using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using VCommon.VApplication.Auditing.DataAnnotations;

namespace VCommon.VApplication.Auditing.Json
{
    internal class JsonAuditLogContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var properties = base.CreateProperties(type, memberSerialization);

            foreach (var prop in properties)
            {
                var attrs = prop.AttributeProvider.GetAttributes(true);

                //检测并禁止JsonIgnore, 提示使用DisableAuditingAttribute
                if (attrs.Any(p => p is JsonIgnoreAttribute)) throw new VAuditModelException($"检测到{nameof(JsonIgnoreAttribute)}特性,要禁用审计日志请使用{nameof(DisableAuditingLogAttribute)}代替. 类:{type.FullName},成员:{prop.UnderlyingName}");

                //用DisableAuditing代替JsonIgnore
                if (attrs.Any(p => p is DisableAuditingLogAttribute)) prop.Ignored = true;

                //实现SimplifyAuditing
                var sim = attrs.OfType<SimplifyAuditingLogAttribute>().SingleOrDefault();
                if (null != sim) prop.Converter = new JsonSimplifyAuditingConverter(sim.MaxLengthAllowed);
            }

            return properties;
        }
    }
}