using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Sonex.UserControls.DataGridView
{
    public sealed partial class DataGridView
    {
        public string? Filter { get; private set; }

        public void SetFilter(string? filter)
        {
            if (ItemsSource == null || ItemsSource.Count == 0 || ItemsType == null)
            {
                return;
            }
            Filter = filter;

            if (string.IsNullOrEmpty(filter))
            {
                _ItemsSourceFiltred = _ItemsSource;
            }
            else
            {
                Filter = Replace(Filter);
                _ItemsSourceFiltred = DynamicFilterRuntime.ApplyWhereToList(
                    items: ItemsSource,
                    itemType: ItemsType,
                    predicate: Filter
                );
            }

            _NeedCalcVerticalScroll = true;
            RequestRender();
        }

        public static string Replace(string query)
        {
            if (string.IsNullOrWhiteSpace(query))
                return query;

            return Regex.Replace(query, @"@\w+", match =>
            {
                return match.Value.ToLower() switch
                {
                    "now" => ToDateTimeLiteral(DateTime.Now),
                    "today" => ToDateTimeLiteral(DateTime.Today),
                    _ => match.Value
                };
            });
        }

        private static string ToDateTimeLiteral(DateTime dt)
            => $"DateTime({dt.Year},{dt.Month},{dt.Day},{dt.Hour},{dt.Minute},{dt.Second})";

        private static string ToDateOnlyLiteral(DateOnly d)
            => $"DateOnly({d.Year},{d.Month},{d.Day})";
    }
}
