using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Linq;

namespace VCommon.VApplication.Auditing.Json
{
    internal class JsonSimplifyAuditingConverter : JsonConverter
    {
        private readonly int _maxLengthAllowed;

        public JsonSimplifyAuditingConverter(int maxLengthAllowed) => _maxLengthAllowed = maxLengthAllowed;

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var jToken = JToken.FromObject(value, serializer);
            var json = jToken.ToString(Formatting.None);

            var length = json.Length;

            if (length <= _maxLengthAllowed)
            {
                writer.WriteRawValue(json);
            }
            else
            {
                //TODO: 进一步调整简化后的内容

                var type = value.GetType().FullName;
                int? count = null;

                //集合
                if (value is IEnumerable collection) count = collection.Cast<object>().Count();

                //字符串
                //一般对象

                JToken.FromObject(new { Count = count, Type = type, Length = length, }).WriteTo(writer);
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => throw new NotImplementedException();

        public override bool CanConvert(Type objectType) => true;
    }
}