using System.Globalization;
namespace Khaemhat.Core.Scheduling;
///
/// A five-field cron expression (minute hour day-of-month month day-of-week) for scheduled tasks (SPEC ยง9.4):
/// *, lists (1,15), ranges (1-5), steps (*/10, 8-18/2); day of week 0-7 with 0 and 7
/// for Sunday. As in classic cron, when both day fields are restricted a day matches either. Times are computed in the
/// task's time zone, so "every day at 02:30" stays at 02:30 across daylight saving changes (a skipped local time is
/// skipped that day).
///
public sealed class CronExpression
{
private readonly bool[] _minutes = new bool[60];
private readonly bool[] _hours = new bool[24];
private readonly bool[] _days = new bool[32];
private readonly bool[] _months = new bool[13];
private readonly bool[] _weekDays = new bool[7];
private readonly bool _anyDay;
private readonly bool _anyWeekDay;
private CronExpression(string text, string[] fields)
{
Text = text;
Fill(fields[0], 0, 59, _minutes);
Fill(fields[1], 0, 23, _hours);
_anyDay = Fill(fields[2], 1, 31, _days);
Fill(fields[3], 1, 12, _months);
var weekDays = new bool[8];
_anyWeekDay = Fill(fields[4], 0, 7, weekDays);
for (var i = 0; i < 7; i++)
{
_weekDays[i] = weekDays[i] || (i == 0 && weekDays[7]);
}
}
/// The expression as written.
public string Text { get; }
/// Parses an expression.
/// The expression.
/// The parsed expression.
/// The expression is not valid.
public static CronExpression Parse(string text) =>
TryParse(text, out var result, out var error) ? result : throw new FormatException(error);
/// Tries to parse an expression.
/// The expression.
/// The parsed expression.
/// Why it is not valid.
/// when valid.
public static bool TryParse(string? text, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out CronExpression? result, out string? error)
{
result = null;
var fields = (text ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length != 5)
{
error = "A cron expression has five fields: minute hour day-of-month month day-of-week.";
return false;
}
try
{
result = new CronExpression(string.Join(' ', fields), fields);
error = null;
return true;
}
catch (FormatException ex)
{
error = ex.Message;
return false;
}
}
/// The first occurrence strictly after a moment.
/// The moment (UTC).
/// The time zone of the schedule.
/// The next occurrence in UTC, or when none exists in the next five years.
public DateTime? NextAfter(DateTime afterUtc, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(zone);
var utc = DateTime.SpecifyKind(afterUtc, DateTimeKind.Utc);
var local = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);
var candidate = new DateTime(local.Year, local.Month, local.Day, local.Hour, local.Minute, 0, DateTimeKind.Unspecified).AddMinutes(1);
var limit = candidate.AddYears(5);
while (candidate < limit)
{
if (!_months[candidate.Month])
{
candidate = new DateTime(candidate.Year, candidate.Month, 1, 0, 0, 0, DateTimeKind.Unspecified).AddMonths(1);
continue;
}
if (!DayMatches(candidate))
{
candidate = candidate.Date.AddDays(1);
continue;
}
if (!_hours[candidate.Hour])
{
candidate = candidate.Date.AddHours(candidate.Hour + 1);
continue;
}
if (!_minutes[candidate.Minute])
{
candidate = candidate.AddMinutes(1);
continue;
}
if (zone.IsInvalidTime(candidate))
{
candidate = candidate.AddMinutes(1);
continue;
}
var result = TimeZoneInfo.ConvertTimeToUtc(candidate, zone);
if (result > utc)
{
return result;
}
candidate = candidate.AddMinutes(1);
}
return null;
}
///
public override string ToString() => Text;
private bool DayMatches(DateTime date)
{
var day = _days[date.Day];
var weekDay = _weekDays[(int)date.DayOfWeek];
return (_anyDay, _anyWeekDay) switch
{
(true, true) => true,
(true, false) => weekDay,
(false, true) => day,
_ => day || weekDay,
};
}
// Fills the allowed values of a field; returns true when the field is "*".
private static bool Fill(string field, int min, int max, bool[] allowed)
{
if (field == "*")
{
for (var i = min; i <= max; i++)
{
allowed[i] = true;
}
return true;
}
foreach (var part in field.Split(','))
{
var step = 1;
var range = part;
var slash = part.IndexOf('/', StringComparison.Ordinal);
if (slash >= 0)
{
step = Number(part[(slash + 1)..], 1, max, part);
range = part[..slash];
}
int from, to;
if (range == "*")
{
(from, to) = (min, max);
}
else if (range.IndexOf('-', StringComparison.Ordinal) is var dash and > 0)
{
from = Number(range[..dash], min, max, part);
to = Number(range[(dash + 1)..], min, max, part);
if (to < from)
{
throw new FormatException($"The range '{part}' goes backwards.");
}
}
else
{
from = Number(range, min, max, part);
to = slash >= 0 ? max : from;
}
for (var i = from; i <= to; i += step)
{
allowed[i] = true;
}
}
return false;
}
private static int Number(string text, int min, int max, string part) =>
int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value >= min && value <= max
? value
: throw new FormatException($"'{part}' is not valid: values go from {min} to {max}.");
}