// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT License.

// <auto-generated/>

#nullable disable

using System;
using System.ClientModel.Primitives;
using System.IO;
using System.Text.Json;
using System.Xml;
using System.Xml.Linq;

namespace SampleTypeSpec
{
    /// <summary>
    /// Base plant with discriminator
    /// Please note this is the abstract base class. The derived classes available for instantiation are: <see cref="Tree"/>.
    /// </summary>
    [PersistableModelProxy(typeof(UnknownPlant))]
    public abstract partial class Plant : IJsonModel<Plant>
    {
        /// <summary> Initializes a new instance of <see cref="Plant"/> for deserialization. </summary>
        internal Plant()
        {
        }

        /// <param name="data"> The data to parse. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        protected virtual Plant PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<Plant>)this).GetFormatFromOptions(options) : options.Format;
            switch (format)
            {
                case "J":
                    using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions))
                    {
                        return DeserializePlant(document.RootElement, options);
                    }
                case "X":
                    using (Stream dataStream = data.ToStream())
                    {
                        return DeserializePlant(XElement.Load(dataStream, LoadOptions.PreserveWhitespace), options);
                    }
                default:
                    throw new FormatException($"The model {nameof(Plant)} does not support reading '{options.Format}' format.");
            }
        }

        /// <param name="options"> The client options for reading and writing models. </param>
        protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<Plant>)this).GetFormatFromOptions(options) : options.Format;
            switch (format)
            {
                case "J":
                    return ModelReaderWriter.Write(this, options, SampleTypeSpecContext.Default);
                case "X":
                    using (MemoryStream stream = new MemoryStream(256))
                    {
                        using (XmlWriter writer = XmlWriter.Create(stream, ModelSerializationExtensions.XmlWriterSettings))
                        {
                            WriteXml(writer, options, "Plant");
                        }
                        if (stream.Position > int.MaxValue)
                        {
                            return BinaryData.FromStream(stream);
                        }
                        else
                        {
                            return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position));
                        }
                    }
                default:
                    throw new FormatException($"The model {nameof(Plant)} does not support writing '{options.Format}' format.");
            }
        }

        /// <param name="options"> The client options for reading and writing models. </param>
        BinaryData IPersistableModel<Plant>.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options);

        /// <param name="data"> The data to parse. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        Plant IPersistableModel<Plant>.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options);

        /// <param name="options"> The client options for reading and writing models. </param>
        string IPersistableModel<Plant>.GetFormatFromOptions(ModelReaderWriterOptions options) => "J";

        /// <param name="writer"> The JSON writer. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        void IJsonModel<Plant>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
        {
            writer.WriteStartObject();
            JsonModelWriteCore(writer, options);
            writer.WriteEndObject();
        }

        /// <param name="writer"> The JSON writer. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<Plant>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(Plant)} does not support writing '{format}' format.");
            }
            writer.WritePropertyName("species"u8);
            writer.WriteStringValue(Species);
            writer.WritePropertyName("id"u8);
            writer.WriteStringValue(Id);
            writer.WritePropertyName("height"u8);
            writer.WriteNumberValue(Height);
            if (options.Format != "W" && _additionalBinaryDataProperties != null)
            {
                foreach (var item in _additionalBinaryDataProperties)
                {
                    writer.WritePropertyName(item.Key);
#if NET6_0_OR_GREATER
                    writer.WriteRawValue(item.Value);
#else
                    using (JsonDocument document = JsonDocument.Parse(item.Value))
                    {
                        JsonSerializer.Serialize(writer, document.RootElement);
                    }
#endif
                }
            }
        }

        /// <param name="reader"> The JSON reader. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        Plant IJsonModel<Plant>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options);

        /// <param name="reader"> The JSON reader. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        protected virtual Plant JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<Plant>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(Plant)} does not support reading '{format}' format.");
            }
            using JsonDocument document = JsonDocument.ParseValue(ref reader);
            return DeserializePlant(document.RootElement, options);
        }

        /// <param name="element"> The JSON element to deserialize. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        internal static Plant DeserializePlant(JsonElement element, ModelReaderWriterOptions options)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            if (element.TryGetProperty("species"u8, out JsonElement discriminator))
            {
                switch (discriminator.GetString())
                {
                    case "tree":
                        return Tree.DeserializeTree(element, options);
                }
            }
            return UnknownPlant.DeserializeUnknownPlant(element, options);
        }

        /// <param name="writer"> The XML writer. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        /// <param name="nameHint"> An optional name hint. </param>
        private void WriteXml(XmlWriter writer, ModelReaderWriterOptions options, string nameHint)
        {
            if (nameHint != null)
            {
                writer.WriteStartElement(nameHint);
            }

            XmlModelWriteCore(writer, options);

            if (nameHint != null)
            {
                writer.WriteEndElement();
            }
        }

        /// <param name="writer"> The XML writer. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        protected virtual void XmlModelWriteCore(XmlWriter writer, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<Plant>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "X")
            {
                throw new FormatException($"The model {nameof(Plant)} does not support writing '{format}' format.");
            }

            writer.WriteStartElement("species");
            writer.WriteValue(Species);
            writer.WriteEndElement();
            writer.WriteStartElement("id");
            writer.WriteValue(Id);
            writer.WriteEndElement();
            writer.WriteStartElement("height");
            writer.WriteValue(Height);
            writer.WriteEndElement();
        }

        /// <param name="element"> The xml element to deserialize. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        internal static Plant DeserializePlant(XElement element, ModelReaderWriterOptions options)
        {
            if (element == null)
            {
                return null;
            }

            XElement discriminatorElement = element.Element("species");
            if (discriminatorElement != null)
            {
                switch ((string)discriminatorElement)
                {
                    case "tree":
                        return Tree.DeserializeTree(element, options);
                }
            }
            return UnknownPlant.DeserializeUnknownPlant(element, options);
        }
    }
}
