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

// <auto-generated/>

#nullable disable

using System;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;

namespace SampleTypeSpec
{
    /// <summary> A sample dynamic model. </summary>
    public partial class DynamicModel : IJsonModel<DynamicModel>
    {
        /// <summary> Initializes a new instance of <see cref="DynamicModel"/> for deserialization. </summary>
        internal DynamicModel()
        {
        }

        /// <param name="data"> The data to parse. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        protected virtual DynamicModel PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<DynamicModel>)this).GetFormatFromOptions(options) : options.Format;
            switch (format)
            {
                case "J":
                    using (JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions))
                    {
                        return DeserializeDynamicModel(document.RootElement, data, options);
                    }
                default:
                    throw new FormatException($"The model {nameof(DynamicModel)} 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<DynamicModel>)this).GetFormatFromOptions(options) : options.Format;
            switch (format)
            {
                case "J":
                    return ModelReaderWriter.Write(this, options, SampleTypeSpecContext.Default);
                default:
                    throw new FormatException($"The model {nameof(DynamicModel)} does not support writing '{options.Format}' format.");
            }
        }

        /// <param name="options"> The client options for reading and writing models. </param>
        BinaryData IPersistableModel<DynamicModel>.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>
        DynamicModel IPersistableModel<DynamicModel>.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options);

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

        /// <param name="dynamicModel"> The <see cref="DynamicModel"/> to serialize into <see cref="BinaryContent"/>. </param>
        public static implicit operator BinaryContent(DynamicModel dynamicModel)
        {
            if (dynamicModel == null)
            {
                return null;
            }
            return BinaryContent.Create(dynamicModel, ModelSerializationExtensions.WireOptions);
        }

        /// <param name="writer"> The JSON writer. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        void IJsonModel<DynamicModel>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
        {
#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
            if (Patch.Contains("$"u8))
            {
                writer.WriteRawValue(Patch.GetJson("$"u8));
                return;
            }
#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.

            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<DynamicModel>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(DynamicModel)} does not support writing '{format}' format.");
            }
#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
            if (!Patch.Contains("$.name"u8))
            {
                writer.WritePropertyName("name"u8);
                writer.WriteStringValue(Name);
            }
            if (Optional.IsDefined(OptionalUnknown) && !Patch.Contains("$.optionalUnknown"u8))
            {
                writer.WritePropertyName("optionalUnknown"u8);
#if NET6_0_OR_GREATER
                writer.WriteRawValue(OptionalUnknown);
#else
                using (JsonDocument document = JsonDocument.Parse(OptionalUnknown))
                {
                    JsonSerializer.Serialize(writer, document.RootElement);
                }
#endif
            }
            if (Optional.IsDefined(OptionalInt) && !Patch.Contains("$.optionalInt"u8))
            {
                writer.WritePropertyName("optionalInt"u8);
                writer.WriteNumberValue(OptionalInt.Value);
            }
            if (Patch.Contains("$.optionalNullableList"u8))
            {
                if (!Patch.IsRemoved("$.optionalNullableList"u8))
                {
                    writer.WritePropertyName("optionalNullableList"u8);
                    writer.WriteRawValue(Patch.GetJson("$.optionalNullableList"u8));
                }
            }
            else if (Optional.IsCollectionDefined(OptionalNullableList))
            {
                writer.WritePropertyName("optionalNullableList"u8);
                writer.WriteStartArray();
                for (int i = 0; i < OptionalNullableList.Count; i++)
                {
                    if (Patch.IsRemoved(Encoding.UTF8.GetBytes($"$.optionalNullableList[{i}]")))
                    {
                        continue;
                    }
                    writer.WriteNumberValue(OptionalNullableList[i]);
                }
                Patch.WriteTo(writer, "$.optionalNullableList"u8);
                writer.WriteEndArray();
            }
            if (Patch.Contains("$.requiredNullableList"u8))
            {
                if (!Patch.IsRemoved("$.requiredNullableList"u8))
                {
                    writer.WritePropertyName("requiredNullableList"u8);
                    writer.WriteRawValue(Patch.GetJson("$.requiredNullableList"u8));
                }
            }
            else if (Optional.IsCollectionDefined(RequiredNullableList))
            {
                writer.WritePropertyName("requiredNullableList"u8);
                writer.WriteStartArray();
                for (int i = 0; i < RequiredNullableList.Count; i++)
                {
                    if (Patch.IsRemoved(Encoding.UTF8.GetBytes($"$.requiredNullableList[{i}]")))
                    {
                        continue;
                    }
                    writer.WriteNumberValue(RequiredNullableList[i]);
                }
                Patch.WriteTo(writer, "$.requiredNullableList"u8);
                writer.WriteEndArray();
            }
            else
            {
                writer.WriteNull("requiredNullableList"u8);
            }
            if (Optional.IsCollectionDefined(OptionalNullableDictionary) && !Patch.Contains("$.optionalNullableDictionary"u8))
            {
                writer.WritePropertyName("optionalNullableDictionary"u8);
                writer.WriteStartObject();
#if NET8_0_OR_GREATER
                global::System.Span<byte> buffer = stackalloc byte[256];
#endif
                foreach (var item in OptionalNullableDictionary)
                {
#if NET8_0_OR_GREATER
                    int bytesWritten = global::System.Text.Encoding.UTF8.GetBytes(item.Key.AsSpan(), buffer);
                    bool patchContains = (bytesWritten == 256) ? Patch.Contains("$.optionalNullableDictionary"u8, global::System.Text.Encoding.UTF8.GetBytes(item.Key)) : Patch.Contains("$.optionalNullableDictionary"u8, buffer.Slice(0, bytesWritten));
#else
                    bool patchContains = Patch.Contains("$.optionalNullableDictionary"u8, Encoding.UTF8.GetBytes(item.Key));
#endif
                    if (!patchContains)
                    {
                        writer.WritePropertyName(item.Key);
                        writer.WriteNumberValue(item.Value);
                    }
                }

                Patch.WriteTo(writer, "$.optionalNullableDictionary"u8);
                writer.WriteEndObject();
            }
            if (Optional.IsCollectionDefined(RequiredNullableDictionary) && !Patch.Contains("$.requiredNullableDictionary"u8))
            {
                writer.WritePropertyName("requiredNullableDictionary"u8);
                writer.WriteStartObject();
#if NET8_0_OR_GREATER
                global::System.Span<byte> buffer = stackalloc byte[256];
#endif
                foreach (var item in RequiredNullableDictionary)
                {
#if NET8_0_OR_GREATER
                    int bytesWritten = global::System.Text.Encoding.UTF8.GetBytes(item.Key.AsSpan(), buffer);
                    bool patchContains = (bytesWritten == 256) ? Patch.Contains("$.requiredNullableDictionary"u8, global::System.Text.Encoding.UTF8.GetBytes(item.Key)) : Patch.Contains("$.requiredNullableDictionary"u8, buffer.Slice(0, bytesWritten));
#else
                    bool patchContains = Patch.Contains("$.requiredNullableDictionary"u8, Encoding.UTF8.GetBytes(item.Key));
#endif
                    if (!patchContains)
                    {
                        writer.WritePropertyName(item.Key);
                        writer.WriteNumberValue(item.Value);
                    }
                }

                Patch.WriteTo(writer, "$.requiredNullableDictionary"u8);
                writer.WriteEndObject();
            }
            else
            {
                writer.WriteNull("requiredNullableDictionary"u8);
            }
            if (!Patch.Contains("$.primitiveDictionary"u8))
            {
                writer.WritePropertyName("primitiveDictionary"u8);
                writer.WriteStartObject();
#if NET8_0_OR_GREATER
                global::System.Span<byte> buffer = stackalloc byte[256];
#endif
                foreach (var item in PrimitiveDictionary)
                {
#if NET8_0_OR_GREATER
                    int bytesWritten = global::System.Text.Encoding.UTF8.GetBytes(item.Key.AsSpan(), buffer);
                    bool patchContains = (bytesWritten == 256) ? Patch.Contains("$.primitiveDictionary"u8, global::System.Text.Encoding.UTF8.GetBytes(item.Key)) : Patch.Contains("$.primitiveDictionary"u8, buffer.Slice(0, bytesWritten));
#else
                    bool patchContains = Patch.Contains("$.primitiveDictionary"u8, Encoding.UTF8.GetBytes(item.Key));
#endif
                    if (!patchContains)
                    {
                        writer.WritePropertyName(item.Key);
                        writer.WriteNumberValue(item.Value);
                    }
                }

                Patch.WriteTo(writer, "$.primitiveDictionary"u8);
                writer.WriteEndObject();
            }
            if (!Patch.Contains("$.foo"u8))
            {
                writer.WritePropertyName("foo"u8);
                writer.WriteObjectValue(Foo, options);
            }
            if (Patch.Contains("$.listFoo"u8))
            {
                if (!Patch.IsRemoved("$.listFoo"u8))
                {
                    writer.WritePropertyName("listFoo"u8);
                    writer.WriteRawValue(Patch.GetJson("$.listFoo"u8));
                }
            }
            else
            {
                writer.WritePropertyName("listFoo"u8);
                writer.WriteStartArray();
                for (int i = 0; i < ListFoo.Count; i++)
                {
                    if (ListFoo[i].Patch.IsRemoved("$"u8))
                    {
                        continue;
                    }
                    writer.WriteObjectValue(ListFoo[i], options);
                }
                Patch.WriteTo(writer, "$.listFoo"u8);
                writer.WriteEndArray();
            }
            if (Patch.Contains("$.listOfListFoo"u8))
            {
                if (!Patch.IsRemoved("$.listOfListFoo"u8))
                {
                    writer.WritePropertyName("listOfListFoo"u8);
                    writer.WriteRawValue(Patch.GetJson("$.listOfListFoo"u8));
                }
            }
            else
            {
                writer.WritePropertyName("listOfListFoo"u8);
                writer.WriteStartArray();
                for (int i = 0; i < ListOfListFoo.Count; i++)
                {
                    if (Patch.IsRemoved(Encoding.UTF8.GetBytes($"$.listOfListFoo[{i}]")))
                    {
                        continue;
                    }
                    if (ListOfListFoo[i] == null)
                    {
                        writer.WriteNullValue();
                        continue;
                    }
                    writer.WriteStartArray();
                    for (int i0 = 0; i0 < ListOfListFoo[i].Count; i0++)
                    {
                        if (ListOfListFoo[i][i0].Patch.IsRemoved("$"u8))
                        {
                            continue;
                        }
                        writer.WriteObjectValue(ListOfListFoo[i][i0], options);
                    }
                    Patch.WriteTo(writer, Encoding.UTF8.GetBytes($"$.listOfListFoo[{i}]"));
                    writer.WriteEndArray();
                }
                Patch.WriteTo(writer, "$.listOfListFoo"u8);
                writer.WriteEndArray();
            }
            if (!Patch.Contains("$.dictionaryFoo"u8))
            {
                writer.WritePropertyName("dictionaryFoo"u8);
                writer.WriteStartObject();
#if NET8_0_OR_GREATER
                global::System.Span<byte> buffer = stackalloc byte[256];
#endif
                foreach (var item in DictionaryFoo)
                {
#if NET8_0_OR_GREATER
                    int bytesWritten = global::System.Text.Encoding.UTF8.GetBytes(item.Key.AsSpan(), buffer);
                    bool patchContains = (bytesWritten == 256) ? Patch.Contains("$.dictionaryFoo"u8, global::System.Text.Encoding.UTF8.GetBytes(item.Key)) : Patch.Contains("$.dictionaryFoo"u8, buffer.Slice(0, bytesWritten));
#else
                    bool patchContains = Patch.Contains("$.dictionaryFoo"u8, Encoding.UTF8.GetBytes(item.Key));
#endif
                    if (!patchContains)
                    {
                        writer.WritePropertyName(item.Key);
                        writer.WriteObjectValue(item.Value, options);
                    }
                }

                Patch.WriteTo(writer, "$.dictionaryFoo"u8);
                writer.WriteEndObject();
            }
            if (!Patch.Contains("$.dictionaryOfDictionaryFoo"u8))
            {
                writer.WritePropertyName("dictionaryOfDictionaryFoo"u8);
                writer.WriteStartObject();
#if NET8_0_OR_GREATER
                global::System.Span<byte> buffer = stackalloc byte[256];
#endif
                foreach (var item in DictionaryOfDictionaryFoo)
                {
#if NET8_0_OR_GREATER
                    int bytesWritten = global::System.Text.Encoding.UTF8.GetBytes(item.Key.AsSpan(), buffer);
                    bool patchContains = (bytesWritten == 256) ? Patch.Contains("$.dictionaryOfDictionaryFoo"u8, global::System.Text.Encoding.UTF8.GetBytes(item.Key)) : Patch.Contains("$.dictionaryOfDictionaryFoo"u8, buffer.Slice(0, bytesWritten));
#else
                    bool patchContains = Patch.Contains("$.dictionaryOfDictionaryFoo"u8, Encoding.UTF8.GetBytes(item.Key));
#endif
                    if (!patchContains)
                    {
                        writer.WritePropertyName(item.Key);
                        if (item.Value == null)
                        {
                            writer.WriteNullValue();
                            continue;
                        }
                        writer.WriteStartObject();
#if NET8_0_OR_GREATER
                        global::System.Span<byte> buffer0 = stackalloc byte[256];
#endif
                        foreach (var item0 in item.Value)
                        {
#if NET8_0_OR_GREATER
                            int bytesWritten0 = global::System.Text.Encoding.UTF8.GetBytes(item0.Key.AsSpan(), buffer0);
                            bool patchContains0 = (bytesWritten0 == 256) ? Patch.Contains(global::System.Text.Encoding.UTF8.GetBytes($"$.dictionaryOfDictionaryFoo[\"{item.Key}\"]"), global::System.Text.Encoding.UTF8.GetBytes(item0.Key)) : Patch.Contains(global::System.Text.Encoding.UTF8.GetBytes($"$.dictionaryOfDictionaryFoo[\"{item.Key}\"]"), buffer0.Slice(0, bytesWritten0));
#else
                            bool patchContains0 = Patch.Contains(Encoding.UTF8.GetBytes($"$.dictionaryOfDictionaryFoo[\"{item.Key}\"]"), Encoding.UTF8.GetBytes(item0.Key));
#endif
                            if (!patchContains0)
                            {
                                writer.WritePropertyName(item0.Key);
                                writer.WriteObjectValue(item0.Value, options);
                            }
                        }

                        Patch.WriteTo(writer, Encoding.UTF8.GetBytes($"$.dictionaryOfDictionaryFoo[\"{item.Key}\"]"));
                        writer.WriteEndObject();
                    }
                }

                Patch.WriteTo(writer, "$.dictionaryOfDictionaryFoo"u8);
                writer.WriteEndObject();
            }
            if (!Patch.Contains("$.dictionaryListFoo"u8))
            {
                writer.WritePropertyName("dictionaryListFoo"u8);
                writer.WriteStartObject();
#if NET8_0_OR_GREATER
                global::System.Span<byte> buffer = stackalloc byte[256];
#endif
                foreach (var item in DictionaryListFoo)
                {
#if NET8_0_OR_GREATER
                    int bytesWritten = global::System.Text.Encoding.UTF8.GetBytes(item.Key.AsSpan(), buffer);
                    bool patchContains = (bytesWritten == 256) ? Patch.Contains("$.dictionaryListFoo"u8, global::System.Text.Encoding.UTF8.GetBytes(item.Key)) : Patch.Contains("$.dictionaryListFoo"u8, buffer.Slice(0, bytesWritten));
#else
                    bool patchContains = Patch.Contains("$.dictionaryListFoo"u8, Encoding.UTF8.GetBytes(item.Key));
#endif
                    if (!patchContains)
                    {
                        writer.WritePropertyName(item.Key);
                        if (item.Value == null)
                        {
                            writer.WriteNullValue();
                            continue;
                        }
                        writer.WriteStartArray();
                        for (int i = 0; i < item.Value.Count; i++)
                        {
                            if (item.Value[i].Patch.IsRemoved("$"u8))
                            {
                                continue;
                            }
                            writer.WriteObjectValue(item.Value[i], options);
                        }
                        Patch.WriteTo(writer, Encoding.UTF8.GetBytes($"$.dictionaryListFoo[\"{item.Key}\"]"));
                        writer.WriteEndArray();
                    }
                }

                Patch.WriteTo(writer, "$.dictionaryListFoo"u8);
                writer.WriteEndObject();
            }
            if (Patch.Contains("$.listOfDictionaryFoo"u8))
            {
                if (!Patch.IsRemoved("$.listOfDictionaryFoo"u8))
                {
                    writer.WritePropertyName("listOfDictionaryFoo"u8);
                    writer.WriteRawValue(Patch.GetJson("$.listOfDictionaryFoo"u8));
                }
            }
            else
            {
                writer.WritePropertyName("listOfDictionaryFoo"u8);
                writer.WriteStartArray();
                for (int i = 0; i < ListOfDictionaryFoo.Count; i++)
                {
                    if (Patch.IsRemoved(Encoding.UTF8.GetBytes($"$.listOfDictionaryFoo[{i}]")))
                    {
                        continue;
                    }
                    if (ListOfDictionaryFoo[i] == null)
                    {
                        writer.WriteNullValue();
                        continue;
                    }
                    writer.WriteStartObject();
#if NET8_0_OR_GREATER
                    global::System.Span<byte> buffer = stackalloc byte[256];
#endif
                    foreach (var item in ListOfDictionaryFoo[i])
                    {
#if NET8_0_OR_GREATER
                        int bytesWritten = global::System.Text.Encoding.UTF8.GetBytes(item.Key.AsSpan(), buffer);
                        bool patchContains = (bytesWritten == 256) ? Patch.Contains(global::System.Text.Encoding.UTF8.GetBytes($"$.listOfDictionaryFoo[{i}]"), global::System.Text.Encoding.UTF8.GetBytes(item.Key)) : Patch.Contains(global::System.Text.Encoding.UTF8.GetBytes($"$.listOfDictionaryFoo[{i}]"), buffer.Slice(0, bytesWritten));
#else
                        bool patchContains = Patch.Contains(Encoding.UTF8.GetBytes($"$.listOfDictionaryFoo[{i}]"), Encoding.UTF8.GetBytes(item.Key));
#endif
                        if (!patchContains)
                        {
                            writer.WritePropertyName(item.Key);
                            writer.WriteObjectValue(item.Value, options);
                        }
                    }

                    Patch.WriteTo(writer, Encoding.UTF8.GetBytes($"$.listOfDictionaryFoo[{i}]"));
                    writer.WriteEndObject();
                }
                Patch.WriteTo(writer, "$.listOfDictionaryFoo"u8);
                writer.WriteEndArray();
            }

            Patch.WriteTo(writer);
#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
        }

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

        /// <param name="element"> The JSON element to deserialize. </param>
        /// <param name="data"> The data to parse. </param>
        /// <param name="options"> The client options for reading and writing models. </param>
        internal static DynamicModel DeserializeDynamicModel(JsonElement element, BinaryData data, ModelReaderWriterOptions options)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            string name = default;
            BinaryData optionalUnknown = default;
            int? optionalInt = default;
            IList<int> optionalNullableList = default;
            IList<int> requiredNullableList = default;
            IDictionary<string, int> optionalNullableDictionary = default;
            IDictionary<string, int> requiredNullableDictionary = default;
            IDictionary<string, int> primitiveDictionary = default;
            AnotherDynamicModel foo = default;
            IList<AnotherDynamicModel> listFoo = default;
            IList<IList<AnotherDynamicModel>> listOfListFoo = default;
            IDictionary<string, AnotherDynamicModel> dictionaryFoo = default;
            IDictionary<string, IDictionary<string, AnotherDynamicModel>> dictionaryOfDictionaryFoo = default;
            IDictionary<string, IList<AnotherDynamicModel>> dictionaryListFoo = default;
            IList<IDictionary<string, AnotherDynamicModel>> listOfDictionaryFoo = default;
#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
            JsonPatch patch = new JsonPatch(data is null ? ReadOnlyMemory<byte>.Empty : data.ToMemory());
#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
            foreach (var prop in element.EnumerateObject())
            {
                if (prop.NameEquals("name"u8))
                {
                    name = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("optionalUnknown"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    optionalUnknown = BinaryData.FromString(prop.Value.GetRawText());
                    continue;
                }
                if (prop.NameEquals("optionalInt"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    optionalInt = prop.Value.GetInt32();
                    continue;
                }
                if (prop.NameEquals("optionalNullableList"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<int> array = new List<int>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(item.GetInt32());
                    }
                    optionalNullableList = array;
                    continue;
                }
                if (prop.NameEquals("requiredNullableList"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        requiredNullableList = new ChangeTrackingList<int>();
                        continue;
                    }
                    List<int> array = new List<int>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(item.GetInt32());
                    }
                    requiredNullableList = array;
                    continue;
                }
                if (prop.NameEquals("optionalNullableDictionary"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    Dictionary<string, int> dictionary = new Dictionary<string, int>();
                    foreach (var prop0 in prop.Value.EnumerateObject())
                    {
                        dictionary.Add(prop0.Name, prop0.Value.GetInt32());
                    }
                    optionalNullableDictionary = dictionary;
                    continue;
                }
                if (prop.NameEquals("requiredNullableDictionary"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        requiredNullableDictionary = new ChangeTrackingDictionary<string, int>();
                        continue;
                    }
                    Dictionary<string, int> dictionary = new Dictionary<string, int>();
                    foreach (var prop0 in prop.Value.EnumerateObject())
                    {
                        dictionary.Add(prop0.Name, prop0.Value.GetInt32());
                    }
                    requiredNullableDictionary = dictionary;
                    continue;
                }
                if (prop.NameEquals("primitiveDictionary"u8))
                {
                    Dictionary<string, int> dictionary = new Dictionary<string, int>();
                    foreach (var prop0 in prop.Value.EnumerateObject())
                    {
                        dictionary.Add(prop0.Name, prop0.Value.GetInt32());
                    }
                    primitiveDictionary = dictionary;
                    continue;
                }
                if (prop.NameEquals("foo"u8))
                {
                    foo = AnotherDynamicModel.DeserializeAnotherDynamicModel(prop.Value, prop.Value.GetUtf8Bytes(), options);
                    continue;
                }
                if (prop.NameEquals("listFoo"u8))
                {
                    List<AnotherDynamicModel> array = new List<AnotherDynamicModel>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(AnotherDynamicModel.DeserializeAnotherDynamicModel(item, item.GetUtf8Bytes(), options));
                    }
                    listFoo = array;
                    continue;
                }
                if (prop.NameEquals("listOfListFoo"u8))
                {
                    List<IList<AnotherDynamicModel>> array = new List<IList<AnotherDynamicModel>>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        if (item.ValueKind == JsonValueKind.Null)
                        {
                            array.Add(null);
                        }
                        else
                        {
                            List<AnotherDynamicModel> array0 = new List<AnotherDynamicModel>();
                            foreach (var item0 in item.EnumerateArray())
                            {
                                array0.Add(AnotherDynamicModel.DeserializeAnotherDynamicModel(item0, item0.GetUtf8Bytes(), options));
                            }
                            array.Add(array0);
                        }
                    }
                    listOfListFoo = array;
                    continue;
                }
                if (prop.NameEquals("dictionaryFoo"u8))
                {
                    Dictionary<string, AnotherDynamicModel> dictionary = new Dictionary<string, AnotherDynamicModel>();
                    foreach (var prop0 in prop.Value.EnumerateObject())
                    {
                        dictionary.Add(prop0.Name, AnotherDynamicModel.DeserializeAnotherDynamicModel(prop0.Value, prop0.Value.GetUtf8Bytes(), options));
                    }
                    dictionaryFoo = dictionary;
                    continue;
                }
                if (prop.NameEquals("dictionaryOfDictionaryFoo"u8))
                {
                    Dictionary<string, IDictionary<string, AnotherDynamicModel>> dictionary = new Dictionary<string, IDictionary<string, AnotherDynamicModel>>();
                    foreach (var prop0 in prop.Value.EnumerateObject())
                    {
                        if (prop0.Value.ValueKind == JsonValueKind.Null)
                        {
                            dictionary.Add(prop0.Name, null);
                        }
                        else
                        {
                            Dictionary<string, AnotherDynamicModel> dictionary0 = new Dictionary<string, AnotherDynamicModel>();
                            foreach (var prop1 in prop0.Value.EnumerateObject())
                            {
                                dictionary0.Add(prop1.Name, AnotherDynamicModel.DeserializeAnotherDynamicModel(prop1.Value, prop1.Value.GetUtf8Bytes(), options));
                            }
                            dictionary.Add(prop0.Name, dictionary0);
                        }
                    }
                    dictionaryOfDictionaryFoo = dictionary;
                    continue;
                }
                if (prop.NameEquals("dictionaryListFoo"u8))
                {
                    Dictionary<string, IList<AnotherDynamicModel>> dictionary = new Dictionary<string, IList<AnotherDynamicModel>>();
                    foreach (var prop0 in prop.Value.EnumerateObject())
                    {
                        if (prop0.Value.ValueKind == JsonValueKind.Null)
                        {
                            dictionary.Add(prop0.Name, null);
                        }
                        else
                        {
                            List<AnotherDynamicModel> array = new List<AnotherDynamicModel>();
                            foreach (var item in prop0.Value.EnumerateArray())
                            {
                                array.Add(AnotherDynamicModel.DeserializeAnotherDynamicModel(item, item.GetUtf8Bytes(), options));
                            }
                            dictionary.Add(prop0.Name, array);
                        }
                    }
                    dictionaryListFoo = dictionary;
                    continue;
                }
                if (prop.NameEquals("listOfDictionaryFoo"u8))
                {
                    List<IDictionary<string, AnotherDynamicModel>> array = new List<IDictionary<string, AnotherDynamicModel>>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        if (item.ValueKind == JsonValueKind.Null)
                        {
                            array.Add(null);
                        }
                        else
                        {
                            Dictionary<string, AnotherDynamicModel> dictionary = new Dictionary<string, AnotherDynamicModel>();
                            foreach (var prop0 in item.EnumerateObject())
                            {
                                dictionary.Add(prop0.Name, AnotherDynamicModel.DeserializeAnotherDynamicModel(prop0.Value, prop0.Value.GetUtf8Bytes(), options));
                            }
                            array.Add(dictionary);
                        }
                    }
                    listOfDictionaryFoo = array;
                    continue;
                }
                patch.Set([.. "$."u8, .. Encoding.UTF8.GetBytes(prop.Name)], prop.Value.GetUtf8Bytes());
            }
            return new DynamicModel(
                name,
                optionalUnknown,
                optionalInt,
                optionalNullableList ?? new ChangeTrackingList<int>(),
                requiredNullableList,
                optionalNullableDictionary ?? new ChangeTrackingDictionary<string, int>(),
                requiredNullableDictionary,
                primitiveDictionary,
                foo,
                listFoo,
                listOfListFoo,
                dictionaryFoo,
                dictionaryOfDictionaryFoo,
                dictionaryListFoo,
                listOfDictionaryFoo,
                patch);
        }

        /// <summary></summary>
        /// <param name="jsonPath"></param>
        /// <param name="value"></param>
        /// <returns></returns>
#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
        private bool PropagateGet(ReadOnlySpan<byte> jsonPath, out JsonPatch.EncodedValue value)
        {
            ReadOnlySpan<byte> local = jsonPath.SliceToStartOfPropertyName();
            value = default;

            if (local.StartsWith("foo"u8))
            {
                return Foo.Patch.TryGetEncodedValue([.. "$"u8, .. local.Slice("foo"u8.Length)], out value);
            }
            if (local.StartsWith("listFoo"u8))
            {
                int propertyLength = "listFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                if (currentSlice.IsEmpty)
                {
                    return TryResolveListFooArray(out value);
                }
                if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
                {
                    return false;
                }
                return ListFoo[index].Patch.TryGetEncodedValue([.. "$"u8, .. currentSlice.Slice(bytesConsumed)], out value);
            }
            if (local.StartsWith("listOfListFoo"u8))
            {
                int propertyLength = "listOfListFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
                {
                    return false;
                }
                currentSlice = currentSlice.Slice(bytesConsumed);
                if (!currentSlice.TryGetIndex(out int index0, out int bytesConsumed0))
                {
                    return false;
                }
                return ListOfListFoo[index][index0].Patch.TryGetEncodedValue([.. "$"u8, .. currentSlice.Slice(bytesConsumed0)], out value);
            }
            if (local.StartsWith("dictionaryFoo"u8))
            {
                int propertyLength = "dictionaryFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                string key = currentSlice.GetFirstPropertyName(out int i);
                if (!DictionaryFoo.TryGetValue(key, out AnotherDynamicModel item))
                {
                    return false;
                }
                return item.Patch.TryGetEncodedValue([.. "$"u8, .. currentSlice.GetRemainder(i)], out value);
            }
            if (local.StartsWith("dictionaryOfDictionaryFoo"u8))
            {
                int propertyLength = "dictionaryOfDictionaryFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                string key = currentSlice.GetFirstPropertyName(out int i);
                if (!DictionaryOfDictionaryFoo.TryGetValue(key, out IDictionary<string, AnotherDynamicModel> item))
                {
                    return false;
                }
                currentSlice = currentSlice.GetRemainder(i);
                string key0 = currentSlice.GetFirstPropertyName(out int i0);
                if (!item.TryGetValue(key0, out AnotherDynamicModel item0))
                {
                    return false;
                }
                return item0.Patch.TryGetEncodedValue([.. "$"u8, .. currentSlice.GetRemainder(i0)], out value);
            }
            if (local.StartsWith("dictionaryListFoo"u8))
            {
                int propertyLength = "dictionaryListFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                string key = currentSlice.GetFirstPropertyName(out int i);
                if (!DictionaryListFoo.TryGetValue(key, out IList<AnotherDynamicModel> item))
                {
                    return false;
                }
                currentSlice = currentSlice.GetRemainder(i);
                if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
                {
                    return false;
                }
                return item[index].Patch.TryGetEncodedValue([.. "$"u8, .. currentSlice.Slice(bytesConsumed)], out value);
            }
            if (local.StartsWith("listOfDictionaryFoo"u8))
            {
                int propertyLength = "listOfDictionaryFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
                {
                    return false;
                }
                currentSlice = currentSlice.Slice(bytesConsumed);
                string key = currentSlice.GetFirstPropertyName(out int i);
                if (!ListOfDictionaryFoo[index].TryGetValue(key, out AnotherDynamicModel item))
                {
                    return false;
                }
                return item.Patch.TryGetEncodedValue([.. "$"u8, .. currentSlice.GetRemainder(i)], out value);
            }
            return false;
        }
#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.

        /// <summary></summary>
        /// <param name="jsonPath"></param>
        /// <param name="value"></param>
        /// <returns></returns>
#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
        private bool PropagateSet(ReadOnlySpan<byte> jsonPath, JsonPatch.EncodedValue value)
        {
            ReadOnlySpan<byte> local = jsonPath.SliceToStartOfPropertyName();

            if (local.StartsWith("foo"u8))
            {
                Foo.Patch.Set([.. "$"u8, .. local.Slice("foo"u8.Length)], value);
                return true;
            }
            if (local.StartsWith("listFoo"u8))
            {
                int propertyLength = "listFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
                {
                    return false;
                }
                ListFoo[index].Patch.Set([.. "$"u8, .. currentSlice.Slice(bytesConsumed)], value);
                return true;
            }
            if (local.StartsWith("listOfListFoo"u8))
            {
                int propertyLength = "listOfListFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
                {
                    return false;
                }
                currentSlice = currentSlice.Slice(bytesConsumed);
                if (!currentSlice.TryGetIndex(out int index0, out int bytesConsumed0))
                {
                    return false;
                }
                ListOfListFoo[index][index0].Patch.Set([.. "$"u8, .. currentSlice.Slice(bytesConsumed0)], value);
                return true;
            }
            if (local.StartsWith("dictionaryFoo"u8))
            {
                int propertyLength = "dictionaryFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                string key = currentSlice.GetFirstPropertyName(out int i);
                if (!DictionaryFoo.TryGetValue(key, out AnotherDynamicModel item))
                {
                    return false;
                }
                item.Patch.Set([.. "$"u8, .. currentSlice.GetRemainder(i)], value);
                return true;
            }
            if (local.StartsWith("dictionaryOfDictionaryFoo"u8))
            {
                int propertyLength = "dictionaryOfDictionaryFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                string key = currentSlice.GetFirstPropertyName(out int i);
                if (!DictionaryOfDictionaryFoo.TryGetValue(key, out IDictionary<string, AnotherDynamicModel> item))
                {
                    return false;
                }
                currentSlice = currentSlice.GetRemainder(i);
                string key0 = currentSlice.GetFirstPropertyName(out int i0);
                if (!item.TryGetValue(key0, out AnotherDynamicModel item0))
                {
                    return false;
                }
                item0.Patch.Set([.. "$"u8, .. currentSlice.GetRemainder(i0)], value);
                return true;
            }
            if (local.StartsWith("dictionaryListFoo"u8))
            {
                int propertyLength = "dictionaryListFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                string key = currentSlice.GetFirstPropertyName(out int i);
                if (!DictionaryListFoo.TryGetValue(key, out IList<AnotherDynamicModel> item))
                {
                    return false;
                }
                currentSlice = currentSlice.GetRemainder(i);
                if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
                {
                    return false;
                }
                item[index].Patch.Set([.. "$"u8, .. currentSlice.Slice(bytesConsumed)], value);
                return true;
            }
            if (local.StartsWith("listOfDictionaryFoo"u8))
            {
                int propertyLength = "listOfDictionaryFoo"u8.Length;
                ReadOnlySpan<byte> currentSlice = local.Slice(propertyLength);
                if (!currentSlice.TryGetIndex(out int index, out int bytesConsumed))
                {
                    return false;
                }
                currentSlice = currentSlice.Slice(bytesConsumed);
                string key = currentSlice.GetFirstPropertyName(out int i);
                if (!ListOfDictionaryFoo[index].TryGetValue(key, out AnotherDynamicModel item))
                {
                    return false;
                }
                item.Patch.Set([.. "$"u8, .. currentSlice.GetRemainder(i)], value);
                return true;
            }
            return false;
        }
#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.

        /// <summary></summary>
        /// <param name="value"></param>
        /// <returns></returns>
#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
        private bool TryResolveListFooArray(out JsonPatch.EncodedValue value)
        {
            value = default;
            BinaryData data = ModelReaderWriter.Write(ActiveListFoo(), ModelReaderWriterOptions.Json, SampleTypeSpecContext.Default);
            JsonPatch tempPatch = new JsonPatch();
            tempPatch.Set("$"u8, data.ToMemory().Span);
            return tempPatch.TryGetEncodedValue("$"u8, out value);
        }
#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.

        /// <summary></summary>
        /// <returns></returns>
#pragma warning disable SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
        private IEnumerable<AnotherDynamicModel> ActiveListFoo()
        {
            if (!Optional.IsCollectionDefined(ListFoo))
            {
                yield break;
            }
            for (int i = 0; i < ListFoo.Count; i++)
            {
                if (!ListFoo[i].Patch.IsRemoved("$"u8))
                {
                    yield return ListFoo[i];
                }
            }
        }
#pragma warning restore SCME0001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
    }
}
