use chrono::{DateTime, Utc};
use regex::Regex;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct TimePair {
sent: DateTime<Utc>,
recv: Option<DateTime<Utc>>,
}
impl TimePair {
pub fn sending() -> Self {
Self {
sent: Utc::now(),
recv: None,
}
}
pub fn receive(&mut self) {
self.recv = Some(Utc::now());
}
#[doc(hidden)]
pub fn into_sending(self) -> Self {
Self { recv: None, ..self }
}
pub fn local(&self) -> DateTime<Utc> {
self.recv.unwrap_or(self.sent)
}
pub fn from_string(s: &str) -> TimePair {
let re = Regex::new(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.[0-9]*Z").unwrap();
let times = re
.captures_iter(s)
.map(|c| c.get(0).map_or("", |s| s.as_str()))
.map(|t| t.parse::<DateTime<Utc>>().unwrap())
.collect::<Vec<_>>();
if times.is_empty() {
TimePair {
sent: Utc::now(), recv: None,
}
} else {
TimePair {
sent: times[0],
recv: times.get(1).copied(),
}
}
}
}