using System;
using System.Text.Json;

namespace Dacryptero.Search.Sorting
{
    public struct SortInfo
    {
        public ReadOnlyMemory<SortInfoEntry> Entries { get; }

        public SortInfo(ReadOnlyMemory<SortInfoEntry> entries)
        {
            Entries = entries;
        }

        public static SortInfo FromSearchable(ISearchable searchable, SortConfig config, double score)
        {
            Memory<SortInfoEntry> entries = new SortInfoEntry[config.Options.Count];
            if (entries.Length == 0)
                return new SortInfo(entries);
            // check for score sorting
            int scoreCount = 0;
            for (int i = 0; i < config.Options.Count; ++i)
                if (config.Options[i].Target == AST.SortOption.SortTarget.Score)
                {
                    entries.Span[i] = new SortInfoEntry("score", score);
                    scoreCount++;
                }
            if (scoreCount == entries.Length)
                return new SortInfo(entries);
            // query the fields and attributes for the required info
            foreach (var entry in searchable.GetSearchParts())
            {
                if (config.OptionIndex.TryGetValue((entry.Type, entry.Name), out int index))
                    entries.Span[index] = SortInfoEntry.FromDbValue(entry.Name, entry.Value);
            }
            // finish
            return new SortInfo(entries);
        }

        public void WriteTo(Utf8JsonWriter writer)
        {
            writer.WriteStartArray();
            for (int i = 0; i < Entries.Length; ++i)
                Entries.Span[i].WriteTo(writer);
            writer.WriteEndArray();
        }
    }
}