use std::{ops::Range, str::FromStr as _};

use chrono::{DateTime, NaiveDateTime, Utc};

use super::{DateTimeSpan, EventCollector};

#[track_caller]
pub(super) fn date_time_span(
    date_start: &str,
    time_start: &str,
    date_end: &str,
    time_end: &str,
) -> DateTimeSpan {
    DateTimeSpan {
        start: datetime_utc(date_start, time_start),
        end: datetime_utc(date_end, time_end),
    }
}

#[track_caller]
pub(super) fn datetime_utc(date: &str, time: &str) -> DateTime<Utc> {
    let s = format!("{date} {time}+00:00");
    DateTime::<Utc>::from_str(&s).unwrap()
}

#[track_caller]
pub(super) fn datetime_naive(date: &str, time: &str) -> NaiveDateTime {
    let s = format!("{date}T{time}");
    NaiveDateTime::from_str(&s).unwrap()
}

impl EventCollector {
    /// Create an `EventCollector` from a CDR datetime range.
    pub fn from_time_range(cdr_time_range: &Range<DateTime<Utc>>) -> Self {
        let session_duration = cdr_time_range
            .end
            .signed_duration_since(cdr_time_range.start);
        Self::with_session_duration(session_duration)
    }
}
