using System.Globalization;
namespace Khaemhat.Application.Querying;
/// How a filter compares a field with its values (SPEC ยง10.7 KhGrid, KhRadar).
public enum ListFilterOperator
{
/// Equal to the value.
Equals = 0,
/// Different from the value.
NotEquals = 1,
/// Text containing the value, ignoring case.
Contains = 2,
/// Text starting with the value, ignoring case.
StartsWith = 3,
/// Greater than the value.
GreaterThan = 4,
/// Greater than or equal to the value.
GreaterOrEqual = 5,
/// Less than the value.
LessThan = 6,
/// Less than or equal to the value.
LessOrEqual = 7,
/// Between the first and the second value, both included.
Between = 8,
/// One of the values.
In = 9,
/// Empty (null, or an empty text).
IsEmpty = 10,
/// Not empty.
IsNotEmpty = 11,
}
///
/// A filter on a field. The values are invariant texts (2026-11-30, 1234.5, true, the name of an
/// enum value), so a filter can be saved in the user settings and read back unchanged.
///
/// The field id.
/// The comparison.
/// The values: none for the empty checks, two for .
public sealed record ListFilter(string Field, ListFilterOperator Operator, IReadOnlyList Values)
{
/// A filter with its values.
/// The field id.
/// The comparison.
/// The values.
/// The filter.
public static ListFilter Of(string field, ListFilterOperator op, params string[] values) => new(field, op, values);
/// The invariant text of a value, as filters keep it.
/// The value.
/// The text.
public static string Text(object? value) => value switch
{
null => string.Empty,
DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
DateTime d => d.ToString("O", CultureInfo.InvariantCulture),
DateTimeOffset d => d.ToString("O", CultureInfo.InvariantCulture),
bool b => b ? "true" : "false",
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
_ => value.ToString() ?? string.Empty,
};
///
public bool Equals(ListFilter? other) =>
other is not null && Field == other.Field && Operator == other.Operator && Values.SequenceEqual(other.Values);
///
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(Field);
hash.Add(Operator);
foreach (var value in Values)
{
hash.Add(value);
}
return hash.ToHashCode();
}
}
/// An ordering on a field.
/// The field id.
/// Whether from the largest.
public sealed record ListSort(string Field, bool Descending = false);
///
/// What a list or radar asks its source: the text typed in the search box, the filters, the ordering and the page.
/// The source answers with a ; with the same request becomes SQL for
/// a repository or runs on rows in memory.
///
public sealed record ListQuery
{
/// The largest page a source returns.
public const int MaxLimit = 1000;
/// The text of the search box: every searchable field is checked.
public string? Search { get; init; }
/// The filters, all of which must hold.
public IReadOnlyList Filters { get; init; } = [];
/// The ordering, first field first.
public IReadOnlyList Sort { get; init; } = [];
/// The rows to skip.
public int Offset { get; init; }
/// The rows to return, at most .
public int Limit { get; init; } = 50;
/// The same request for another page.
/// The rows to skip.
/// The rows to return.
/// The request.
public ListQuery WithPage(int offset, int limit) => this with { Offset = Math.Max(0, offset), Limit = Math.Clamp(limit, 1, MaxLimit) };
/// Whether two requests select and order the same rows, whatever the page.
/// The other request.
/// Whether they match.
public bool SameRows(ListQuery? other) =>
other is not null && string.Equals(Search?.Trim(), other.Search?.Trim(), StringComparison.OrdinalIgnoreCase)
&& Filters.SequenceEqual(other.Filters) && Sort.SequenceEqual(other.Sort);
}
/// A page of rows with the count and the totals of every row the request selects (not only the page).
/// The row type.
/// The rows of the page.
/// The rows selected.
/// The sums by field id, for the totals row of the grid.
public sealed record ListPage(IReadOnlyList Items, long Total, IReadOnlyDictionary Totals)
{
/// No rows.
#pragma warning disable CA1000 // An empty page of the same row type is the natural default.
public static ListPage Empty { get; } = new([], 0, new Dictionary());
#pragma warning restore CA1000
}
/// Where a grid or radar reads its rows.
/// The row type.
/// The request.
/// Cancellation, when a newer request replaces this one.
/// The page.
public delegate Task> ListSource(ListQuery query, CancellationToken cancellationToken);