using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using API.Data.Misc;
using API.Entities;
using API.Entities.Enums;
using API.Entities.Metadata;
using Microsoft.AspNetCore.Identity;
namespace API.Extensions;
#nullable enable
public static class EnumerableExtensions
{
    private static readonly Regex Regex = new Regex(@"\d+", RegexOptions.Compiled, TimeSpan.FromMilliseconds(500));
    /// 
    /// A natural sort implementation
    /// 
    /// IEnumerable to process
    /// Function that produces a string. Does not support null values
    /// Defaults to CurrentCulture
    /// 
    /// Sorted Enumerable
    public static IEnumerable OrderByNatural(this IEnumerable items, Func selector, StringComparer? stringComparer = null)
    {
        var list = items.ToList();
        var maxDigits = list
            .SelectMany(i => Regex.Matches(selector(i))
                .Select(digitChunk => (int?)digitChunk.Value.Length))
            .Max() ?? 0;
        return list.OrderBy(i => Regex.Replace(selector(i), match => match.Value.PadLeft(maxDigits, '0')), stringComparer ?? StringComparer.CurrentCulture);
    }
    public static IEnumerable RestrictAgainstAgeRestriction(this IEnumerable items, AgeRestriction restriction)
    {
        if (restriction.AgeRating == AgeRating.NotApplicable) return items;
        var q = items.Where(s => s.AgeRating <= restriction.AgeRating);
        if (!restriction.IncludeUnknowns)
        {
            return q.Where(s => s.AgeRating != AgeRating.Unknown);
        }
        return q;
    }
    public static IEnumerable RestrictAgainstAgeRestriction(this IEnumerable items, AgeRestriction restriction)
    {
        if (restriction.AgeRating == AgeRating.NotApplicable) return items;
        var q = items.Where(s => s.AgeRating <= restriction.AgeRating);
        if (!restriction.IncludeUnknowns)
        {
            return q.Where(s => s.AgeRating != AgeRating.Unknown);
        }
        return q;
    }
    public static IEnumerable RestrictAgainstAgeRestriction(this IEnumerable items, AgeRestriction restriction)
    {
        if (restriction.AgeRating == AgeRating.NotApplicable) return items;
        var q = items.Where(s => s.AgeRating <= restriction.AgeRating);
        if (!restriction.IncludeUnknowns)
        {
            return q.Where(s => s.AgeRating != AgeRating.Unknown);
        }
        return q;
    }
}