using System;
using System.Text.Json;

namespace Dacryptero.Web.Events.Send
{
    public class SearchResponse : SendBase
    {
        public string Query { get; }

        public string? UiId { get; }

        public int Order { get; }

        public bool IsLast { get; }

        public double ElapsedSeconds { get; }

        public Search.Sorting.SortConfig SortConfig { get; }

        public ReadOnlyMemory<Search.SearchResult> Results { get; }

        public SearchResponse(string query, string? uiId, int order, bool isLast,
            double elapsedSeconds, Search.Sorting.SortConfig sortConfig,
            ReadOnlyMemory<Search.SearchResult> result)
        {
            Query = query;
            UiId = uiId;
            Order = order;
            IsLast = isLast;
            ElapsedSeconds = elapsedSeconds;
            SortConfig = sortConfig;
            Results = result;
        }

        protected override void WriteJsonContent(Utf8JsonWriter writer)
        {
            writer.WriteString("query", Query);
            if (UiId is not null)
                writer.WriteString("uiId", UiId);
            writer.WriteBoolean("isLast", IsLast);
            writer.WriteNumber("order", Order);
            writer.WriteNumber("elapsed-seconds", ElapsedSeconds);
            writer.WritePropertyName("sorting");
            SortConfig.WriteTo(writer);
            writer.WriteStartArray("result");

            foreach (var entry in Results.Span)
                entry.WriteTo(writer);

            writer.WriteEndArray();
        }
    }
}