using Newtonsoft.Json;

namespace LLM.Editor.Helper
{
    public static class JsonWriter
    {
        public static string ToJson<T>(this T obj, JsonSerializerSettings settings = null) where T : class
        {
            settings ??= _defaultSettings;
            return JsonConvert.SerializeObject(obj, settings);
        }
        
        public static string ToJson<T>(this T obj, bool prettyPrint, JsonSerializerSettings settings = null) where T : class
        {
            settings ??= _defaultSettings;
            settings.Formatting = prettyPrint ? Formatting.Indented : Formatting.None;
            return JsonConvert.SerializeObject(obj, settings);
        }
        
        public static T FromJson<T>(this string json, JsonSerializerSettings settings = null) where T : class
        {
            settings ??= _defaultSettings;
            return JsonConvert.DeserializeObject<T>(json, settings);
        }
        
        private static readonly JsonSerializerSettings _defaultSettings = new()
        {
            Formatting = Formatting.None,
            NullValueHandling = NullValueHandling.Ignore,
            DefaultValueHandling = DefaultValueHandling.Include,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            Converters = UnityTypeConverters.Converters
        };
    }
}