namespace ByteBard.AsyncAPI.Readers
{
    using System.Collections.Generic;
    using ByteBard.AsyncAPI.Extensions;
    using ByteBard.AsyncAPI.Models;
    using ByteBard.AsyncAPI.Readers.ParseNodes;
    using System.Linq;

    internal static partial class AsyncApiV2Deserializer
    {
        private static FixedFieldMap<AsyncApiParameter> parameterFixedFields = new()
        {
            { "description", (a, n) => { a.Description = n.GetScalarValue(); } },
            { "schema", (a, n) => { LoadParameterFromSchema(a, n); } },
            { "location", (a, n) => { a.Location = n.GetScalarValue(); } },
        };

        private static PatternFieldMap<AsyncApiParameter> parameterPatternFields =
            new()
            {
                { s => s.StartsWith("x-"), (a, p, n) => a.AddExtension(p, LoadExtension(p, n)) },
            };

        private static void LoadParameterFromSchema(AsyncApiParameter instance, ParseNode node)
        {
            var schema = AsyncApiJsonSchemaDeserializer.LoadSchema(node);
            if (schema is AsyncApiJsonSchemaReference schemaReference)
            {
                var existingReferences = node.Context.GetFromTempStorage<Dictionary<AsyncApiParameter, AsyncApiJsonSchemaReference>>(TempStorageKeys.ParameterSchemaReferences) ?? new Dictionary<AsyncApiParameter, AsyncApiJsonSchemaReference>();
                existingReferences.Add(instance, schemaReference);
                node.Context.SetTempStorage(TempStorageKeys.ParameterSchemaReferences, existingReferences);
                return;
            }

            if (schema.Enum.Any())
            {
                instance.Enum = schema.Enum.Select(e => e.GetValue<string>()).ToList();
            }

            if (schema.Default != null)
            {
                instance.Default = schema.Default.GetValue<string>();
            }

            if (schema.Examples.Any())
            {
                instance.Examples = schema.Examples.Select(e => e.GetValue<string>()).ToList();
            }
        }

        public static AsyncApiParameter LoadParameter(ParseNode node)
        {
            var mapNode = node.CheckMapNode("parameter");

            var pointer = mapNode.GetReferencePointer();
            if (pointer != null)
            {
                return new AsyncApiParameterReference(pointer);
            }

            var parameter = new AsyncApiParameter();

            ParseMap(mapNode, parameter, parameterFixedFields, parameterPatternFields);

            return parameter;
        }
    }
}