use chrono::{DateTime, Duration, Utc};
use super::gate::SourceGate;
use super::schedule::{QueryContext, RuleSet, find_occurrence};
use crate::calendar::local_time::bounded_utc;
use crate::calendar::rule::SessionKind;
const SESSION_LOOKAHEAD_DAYS: i64 = 14;
type SessionBounds = (DateTime<Utc>, DateTime<Utc>);
fn merge_occurrences_on_day<G: SourceGate>(
context: &QueryContext<'_, G>,
day: chrono::NaiveDate,
kind: SessionKind,
bounds: &mut SessionBounds,
) -> Result<(), G::Error> {
let _: Option<()> = find_occurrence(
context,
day,
RuleSet::Sessions(kind),
false,
|open, close| {
if open <= bounds.1 && close >= bounds.0 {
bounds.0 = bounds.0.min(open);
bounds.1 = bounds.1.max(close);
}
None
},
)?;
Ok(())
}
fn coalesce_same_kind<G: SourceGate>(
context: &QueryContext<'_, G>,
seed: SessionBounds,
kind: SessionKind,
) -> Result<SessionBounds, G::Error> {
if !context.joins_adjacent_same_kind() {
return Ok(seed);
}
if !context.has_daily_close_at(seed.0) {
return Ok(seed);
}
let tz = context.tz();
let mut bounds = seed;
for _ in 0..=SESSION_LOOKAHEAD_DAYS {
let before = bounds;
let start_day = bounded_utc(bounds.0, tz).with_timezone(&tz).date_naive();
let end_day = bounded_utc(bounds.1, tz).with_timezone(&tz).date_naive();
for boundary_day in [start_day, end_day] {
if let Some(previous_day) = boundary_day.pred_opt() {
merge_occurrences_on_day(context, previous_day, kind, &mut bounds)?;
}
merge_occurrences_on_day(context, boundary_day, kind, &mut bounds)?;
}
if bounds == before {
break;
}
}
Ok(bounds)
}
fn containing_occurrence_of_kind<G: SourceGate>(
context: &QueryContext<'_, G>,
instant: DateTime<Utc>,
day: chrono::NaiveDate,
kind: SessionKind,
) -> Result<Option<SessionBounds>, G::Error> {
let hit = |open: DateTime<Utc>, close: DateTime<Utc>| {
(open <= instant && instant < close).then_some((open, close))
};
if let Some(found) = find_occurrence(context, day, RuleSet::Sessions(kind), false, hit)? {
return Ok(Some(found));
}
let Some(yesterday) = day.pred_opt() else {
return Ok(None);
};
if !context.wrapped_occurrence_possible(yesterday, RuleSet::Sessions(kind)) {
return Ok(None);
}
find_occurrence(context, yesterday, RuleSet::Sessions(kind), true, hit)
}
fn containing_concrete_kind<G: SourceGate>(
context: &QueryContext<'_, G>,
instant: DateTime<Utc>,
kind: SessionKind,
) -> Result<Option<SessionBounds>, G::Error> {
let day = bounded_utc(instant, context.tz())
.with_timezone(&context.tz())
.date_naive();
containing_occurrence_of_kind(context, instant, day, kind)?
.map(|candidate| coalesce_same_kind(context, candidate, kind))
.transpose()
}
pub(super) fn contains_in_session_on<G: SourceGate>(
context: &QueryContext<'_, G>,
instant: DateTime<Utc>,
day: chrono::NaiveDate,
kind: SessionKind,
) -> Result<bool, G::Error> {
let found = match kind {
SessionKind::Regular => {
containing_occurrence_of_kind(context, instant, day, SessionKind::Regular)?
}
SessionKind::Extended => {
containing_occurrence_of_kind(context, instant, day, SessionKind::Extended)?
}
SessionKind::Both => {
let regular =
containing_occurrence_of_kind(context, instant, day, SessionKind::Regular)?;
if regular.is_some() {
regular
} else {
containing_occurrence_of_kind(context, instant, day, SessionKind::Extended)?
}
}
};
Ok(found.is_some())
}
pub(in crate::calendar) fn session_bounds_with<G: SourceGate>(
context: &QueryContext<'_, G>,
instant: DateTime<Utc>,
kind: SessionKind,
) -> Result<Option<SessionBounds>, G::Error> {
context.require_floor_at(instant)?;
match containing_session_with(context, instant, kind)? {
Some(bounds) => Ok(Some(bounds)),
None => next_session_after_with(context, instant, kind),
}
}
pub(in crate::calendar) fn containing_session_with<G: SourceGate>(
context: &QueryContext<'_, G>,
instant: DateTime<Utc>,
kind: SessionKind,
) -> Result<Option<SessionBounds>, G::Error> {
match kind {
SessionKind::Regular => containing_concrete_kind(context, instant, SessionKind::Regular),
SessionKind::Extended => containing_concrete_kind(context, instant, SessionKind::Extended),
SessionKind::Both => {
match containing_concrete_kind(context, instant, SessionKind::Regular)? {
Some(bounds) => Ok(Some(bounds)),
None => containing_concrete_kind(context, instant, SessionKind::Extended),
}
}
}
}
fn next_occurrence_after_on_day<G: SourceGate>(
context: &QueryContext<'_, G>,
day: chrono::NaiveDate,
instant: DateTime<Utc>,
kind: SessionKind,
) -> Result<Option<SessionBounds>, G::Error> {
let mut best = None;
let error = find_occurrence(
context,
day,
RuleSet::Sessions(kind),
false,
|open, close| {
if open > instant {
match coalesce_same_kind(context, (open, close), kind) {
Ok(merged) => {
if merged.0 > instant
&& best.is_none_or(|current: SessionBounds| merged.0 < current.0)
{
best = Some(merged);
}
}
Err(error) => return Some(error),
}
}
None
},
)?;
match error {
Some(error) => Err(error),
None => Ok(best),
}
}
fn consider_next_on_day<G: SourceGate>(
context: &QueryContext<'_, G>,
day: chrono::NaiveDate,
instant: DateTime<Utc>,
kind: SessionKind,
best: &mut Option<SessionBounds>,
) -> Result<(), G::Error> {
if let Some(merged) = next_occurrence_after_on_day(context, day, instant, kind)?
&& best.is_none_or(|current| merged.0 < current.0)
{
*best = Some(merged);
}
Ok(())
}
pub(in crate::calendar) fn next_session_after_with<G: SourceGate>(
context: &QueryContext<'_, G>,
instant: DateTime<Utc>,
kind: SessionKind,
) -> Result<Option<SessionBounds>, G::Error> {
context.require_floor_at(instant)?;
let tz = context.tz();
let base_day = bounded_utc(instant, tz).with_timezone(&tz).date_naive();
for offset in 0..=SESSION_LOOKAHEAD_DAYS {
let Some(day) = base_day.checked_add_signed(Duration::days(offset)) else {
break;
};
let mut best = None;
match kind {
SessionKind::Regular => {
consider_next_on_day(context, day, instant, SessionKind::Regular, &mut best)?;
}
SessionKind::Extended => {
consider_next_on_day(context, day, instant, SessionKind::Extended, &mut best)?;
}
SessionKind::Both => {
consider_next_on_day(context, day, instant, SessionKind::Regular, &mut best)?;
consider_next_on_day(context, day, instant, SessionKind::Extended, &mut best)?;
}
}
if best.is_some() {
return Ok(best);
}
}
Ok(None)
}
fn previous_occurrence_before_on_day<G: SourceGate>(
context: &QueryContext<'_, G>,
day: chrono::NaiveDate,
instant: DateTime<Utc>,
kind: SessionKind,
) -> Result<Option<SessionBounds>, G::Error> {
let mut best = None;
let error = find_occurrence(
context,
day,
RuleSet::Sessions(kind),
false,
|open, close| {
if close <= instant {
match coalesce_same_kind(context, (open, close), kind) {
Ok(merged) => {
if merged.1 <= instant
&& best.is_none_or(|current: SessionBounds| merged.1 > current.1)
{
best = Some(merged);
}
}
Err(error) => return Some(error),
}
}
None
},
)?;
match error {
Some(error) => Err(error),
None => Ok(best),
}
}
fn consider_previous_on_day<G: SourceGate>(
context: &QueryContext<'_, G>,
day: chrono::NaiveDate,
instant: DateTime<Utc>,
kind: SessionKind,
best: &mut Option<SessionBounds>,
) -> Result<(), G::Error> {
if let Some(merged) = previous_occurrence_before_on_day(context, day, instant, kind)?
&& best.is_none_or(|current| merged.1 > current.1)
{
*best = Some(merged);
}
Ok(())
}
pub(super) fn previous_session_before_with<G: SourceGate>(
context: &QueryContext<'_, G>,
instant: DateTime<Utc>,
kind: SessionKind,
) -> Result<Option<SessionBounds>, G::Error> {
let tz = context.tz();
let base_day = bounded_utc(instant, tz).with_timezone(&tz).date_naive();
let mut best = None;
let mut scan_one_older_day = false;
for offset in 0..=SESSION_LOOKAHEAD_DAYS {
let Some(day) = base_day.checked_sub_signed(Duration::days(offset)) else {
break;
};
match kind {
SessionKind::Regular => {
consider_previous_on_day(context, day, instant, SessionKind::Regular, &mut best)?;
}
SessionKind::Extended => {
consider_previous_on_day(context, day, instant, SessionKind::Extended, &mut best)?;
}
SessionKind::Both => {
consider_previous_on_day(context, day, instant, SessionKind::Regular, &mut best)?;
consider_previous_on_day(context, day, instant, SessionKind::Extended, &mut best)?;
}
}
if best.is_some() {
if scan_one_older_day {
break;
}
scan_one_older_day = true;
}
}
Ok(best)
}