using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;

namespace TEAMModelOS.SDK.Extension
{
    public static class JsonExtensions
    {
        public static string ToJsonString(this JsonDocument jdoc)
        {
            var bufferWriter = new ArrayBufferWriter<byte>();
            using var writer = new Utf8JsonWriter(bufferWriter, new JsonWriterOptions { Indented = true });
            jdoc.WriteTo(writer);
            writer.Flush();
            return Encoding.UTF8.GetString(bufferWriter.WrittenSpan);
        }

        public static string ToJsonString(this JsonElement jelement)
        {
            var bufferWriter = new ArrayBufferWriter<byte>();
            using var writer = new Utf8JsonWriter(bufferWriter, new JsonWriterOptions { Indented = true });
            jelement.WriteTo(writer);
            writer.Flush();
            return Encoding.UTF8.GetString(bufferWriter.WrittenSpan);
        }

        public static string ToJsonString(this Object obj, JsonSerializerOptions option = null)
        {
            var json = JsonSerializer.Serialize(obj, option);
            return json;
        }

        public static T ToObject<T>(this string json, JsonSerializerOptions option = null)
        {
            var obj = JsonSerializer.Deserialize<T>(json);
            return obj;
        }


        public static T ToObject<T>(this JsonDocument jdoc, JsonSerializerOptions options = null)
        {
            return jdoc.RootElement.ToObject<T>(options);
        }

        public static T ToObject<T>(this JsonElement jelement, JsonSerializerOptions options = null)
        {
            var bufferWriter = new ArrayBufferWriter<byte>();
            using var writer = new Utf8JsonWriter(bufferWriter);
            jelement.WriteTo(writer);
            writer.Flush();
            return JsonSerializer.Deserialize<T>(bufferWriter.WrittenSpan, options);
        }        
    }
}
