mod datetime_requests;
use super::{bounded, endpoint};
use crate::plugins::{calendar, compositions::Compositions, integer_queries, model_coordinates};
use crate::{Context, Error, Outcome, re};
use chrono::{Datelike, Duration, NaiveDate, Weekday};
use num_traits::ToPrimitive;
fn error(name: &str) -> Error {
Error(name.into())
}
fn date(input: &str, context: &Context) -> Result<NaiveDate, Error> {
calendar::date(input, context).ok_or_else(|| error("invalid_endpoint"))
}
fn count(input: &str) -> Result<i64, Error> {
let words = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
];
let normalized = words
.iter()
.position(|word| input.eq_ignore_ascii_case(word))
.map(|n| n.to_string())
.unwrap_or_else(|| input.to_owned());
integer_queries::value(&normalized)?
.to_i64()
.ok_or_else(|| error("integer_limit"))
}
fn dates(kind: &str, values: &[NaiveDate]) -> Result<String, Error> {
bounded(format!(
"calendar_dates({kind}|{})",
values
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(";")
))
}
pub(super) fn rewrite(engine: &Compositions, input: &str, context: &Context) -> Outcome {
if let Some(result) = datetime_requests::rewrite(engine, input, context) {
return Some(result);
}
if let Some(c) = re!(r"(?i)^a project has (.+?) working days starting (monday|tuesday|wednesday|thursday|friday|saturday|sunday) (.+?), with no public holidays and monday-to-friday workweeks; what is its final working day if the start date counts as day one$").captures(input) {
return Some((|| {
let source = date(&c[3], context)?;
if !source.format("%A").to_string().eq_ignore_ascii_case(&c[2])
|| matches!(source.weekday(), Weekday::Sat | Weekday::Sun)
{
return Err(error("invalid_endpoint"));
}
let days = count(&c[1])?;
if days <= 0 { return Err(error("invalid_duration")); }
if days > 100_000 { return Err(error("integer_limit")); }
let target = calendar::workdays(source, (days - 1) as f64, false)
.ok_or_else(|| error("invalid_endpoint"))?;
dates("final", &[target])
})());
}
let pattern = re!(r"(?i)^what date and local time is (.+?) after (.+)$");
if let Some(c) = pattern.captures(input) {
return Some((|| {
let seconds = model_coordinates::read(&c[1], "seconds", engine, context)?.value;
if !seconds.is_integer() {
return Err(error("integer_required"));
}
endpoint::shifted(
&c[2],
seconds
.to_integer()
.to_i64()
.ok_or_else(|| error("integer_limit"))?,
context,
)
})());
}
let pattern = re!(
r"(?i)^what date and weekday is (.+?) calendar days after (.+?), counting the next date as day one$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let source = date(&c[2], context)?;
let days = count(&c[1])?;
let target = calendar::add(source, days as f64, "days")
.ok_or_else(|| error("invalid_endpoint"))?;
dates("weekday", &[target])
})());
}
let pattern = re!(
r"(?i)^a person born (.+?) is how many completed years and months old on (.+?), using calendar anniversaries and month-end clipping$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let born = date(&c[1], context)?;
let as_of = date(&c[2], context)?;
if as_of < born {
return Err(error("invalid_interval"));
}
let months = calendar::interval(born, as_of, "months");
Ok(format!(
"calendar_age_months({}|{})",
months / 12,
months % 12
))
})());
}
let pattern =
re!(r"(?i)^how many calendar days are in the interval from (.+?) through (.+?) inclusive$");
if let Some(c) = pattern.captures(input) {
return Some((|| {
let start = date(&c[1], context)?;
let end = date(&c[2], context)?;
if end < start {
return Err(error("invalid_interval"));
}
Ok(format!(
"calendar_days({})",
calendar::interval(start, end, "days") + 1
))
})());
}
let pattern = re!(
r"(?i)^a deadline is (.+?) business days after (monday|tuesday|wednesday|thursday|friday|saturday|sunday) (.+?); count monday-friday only and ignore holidays$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let source = date(&c[3], context)?;
if !source.format("%A").to_string().eq_ignore_ascii_case(&c[2]) {
return Err(error("invalid_endpoint"));
}
let days = count(&c[1])?;
let target = calendar::workdays(source, days as f64, false)
.ok_or_else(|| error("invalid_endpoint"))?;
dates("final", &[target])
})());
}
let pattern = re!(
r"(?i)^a person was born on (.+?); how many whole years old are they on (.+?), using the convention that age increments on february 28 in non-leap years$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let born = date(&c[1], context)?;
let as_of = date(&c[2], context)?;
if as_of < born {
return Err(error("invalid_interval"));
}
let anniversary = NaiveDate::from_ymd_opt(as_of.year(), born.month(), born.day())
.or_else(|| NaiveDate::from_ymd_opt(as_of.year(), 2, 28))
.ok_or_else(|| error("invalid_endpoint"))?;
let years = as_of.year() - born.year() - i32::from(as_of < anniversary);
Ok(format!("calendar_age({years})"))
})());
}
let pattern = re!(
r"(?i)^how many weekdays are between (.+?) and (.+?) inclusive, counting monday through friday and ignoring public holidays$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let start = date(&c[1], context)?;
let end = date(&c[2], context)?;
let days = (end - start).num_days();
if days < 0 {
return Err(error("invalid_interval"));
}
if days > 100_000 {
return Err(error("integer_limit"));
}
let weekdays = (0..=days)
.filter(|offset| {
!matches!(
(start + Duration::days(*offset)).weekday(),
Weekday::Sat | Weekday::Sun
)
})
.count();
Ok(format!("calendar_weekdays({weekdays})"))
})());
}
let pattern = re!(
r"(?i)^a project begins (.+?) and lasts (.+?) calendar days including the start date; what is the final date$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let start = date(&c[1], context)?;
let days = count(&c[2])?;
if days <= 0 {
return Err(error("invalid_duration"));
}
let end = start
.checked_add_signed(
Duration::try_days(days - 1).ok_or_else(|| error("integer_limit"))?,
)
.ok_or_else(|| error("invalid_endpoint"))?;
dates("final", &[end])
})());
}
let pattern = re!(
r"(?i)^a subscription starts on (.+?) and renews monthly on the original day of the month; when that day is missing use the last day of that month\. give the first (.+?) renewal dates$"
);
if let Some(c) = pattern.captures(input) {
return Some((|| {
let start = date(&c[1], context)?;
let count = count(&c[2])?;
if !(1..=1_000).contains(&count) {
return Err(error("integer_limit"));
}
let values = (1..=count)
.map(|month| {
calendar::add(start, month as f64, "months")
.ok_or_else(|| error("invalid_endpoint"))
})
.collect::<Result<Vec<_>, _>>()?;
dates("renewals", &values)
})());
}
None
}
pub(super) fn evaluate(input: &str) -> Outcome {
if let Some(result) = datetime_requests::evaluate(input) {
return Some(result);
}
let pattern = re!(r"^calendar_(age|weekdays|days)\((\d+)\)$");
if let Some(c) = pattern.captures(input) {
return Some(Ok(format!(
"{} {}",
&c[2],
match &c[1] {
"age" => "years",
"days" => "days",
_ => "weekdays",
}
)));
}
if let Some(c) = re!(r"^calendar_age_months\((\d+)\|(\d+)\)$").captures(input) {
return Some((|| {
let months: u32 = c[2].parse().map_err(|_| error("invalid_expression"))?;
if months >= 12 {
return Err(error("invalid_expression"));
}
Ok(format!("{} years; {months} months", &c[1]))
})());
}
if let Some(inner) = input
.strip_prefix("calendar_dates(")
.and_then(|s| s.strip_suffix(')'))
{
return Some((|| {
let (kind, values) = inner
.split_once('|')
.ok_or_else(|| error("invalid_expression"))?;
let values = values
.split(';')
.map(|value| {
NaiveDate::parse_from_str(value, "%Y-%m-%d")
.map_err(|_| error("invalid_endpoint"))
})
.collect::<Result<Vec<_>, _>>()?;
match kind {
"final" if values.len() == 1 => Ok(values[0].format("%-d %B %Y").to_string()),
"weekday" if values.len() == 1 => Ok(format!(
"date: {}; weekday: {}",
values[0].format("%-d %B %Y"),
values[0].format("%A")
)),
"renewals" if !values.is_empty() => bounded(format!(
"renewals: {}",
values
.iter()
.map(|date| date.format("%-d %B %Y").to_string())
.collect::<Vec<_>>()
.join("; ")
)),
_ => Err(error("invalid_expression")),
}
})());
}
let pattern = re!(r"^calendar_instant\(([^|]+)\|(\d+)\|([^|]+)\)$");
if let Some(c) = pattern.captures(input) {
return Some((|| {
let date = NaiveDate::parse_from_str(&c[1], "%Y-%m-%d")
.map_err(|_| error("invalid_endpoint"))?;
let seconds: u32 = c[2].parse().map_err(|_| error("invalid_endpoint"))?;
if seconds >= 86_400 {
return Err(error("invalid_endpoint"));
}
let zone = chrono_tz::TZ_VARIANTS
.iter()
.find(|zone| zone.name().eq_ignore_ascii_case(&c[3]))
.map(|zone| zone.to_string())
.unwrap_or_else(|| c[3].to_ascii_uppercase());
if !endpoint::zone_token(&zone) {
return Err(error("invalid_endpoint"));
}
let hour = seconds / 3_600;
let second = seconds % 60;
let clock = format!(
"{}:{:02}{} {}",
if hour.is_multiple_of(12) {
12
} else {
hour % 12
},
seconds / 60 % 60,
if second == 0 {
String::new()
} else {
format!(":{second:02}")
},
if hour < 12 { "am" } else { "pm" }
);
Ok(format!("{} at {clock} {zone}", date.format("%-d %B %Y")))
})());
}
None
}