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

namespace VCommon.VOpenApi.Json
{
    internal class JsonReturnValueContractResolver : 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, 提示使用OutputIgnoreAttribute
                if (attrs.Any(p => p is JsonIgnoreAttribute)) throw new VAuditModelException($"检测到{nameof(JsonIgnoreAttribute)}特性,要忽略输出请使用{nameof(OutputIgnoreAttribute)}代替. 类:{type.FullName},成员:{prop.UnderlyingName}");

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

            return properties;
        }
    }
}