use jiff::Timestamp;
use jiff::civil::Date;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use crate::de::{
flexible_f64, flexible_int, flexible_string, ist_timestamp, lenient, lenient_vec, parse_ist,
parse_utc,
};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TripMonth {
pub totals: TripTotals,
pub days: Vec<TripDayCount>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TripDayCount {
pub date: Date,
pub trips: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TripTotals {
pub drive_minutes: Option<u32>,
pub idle_minutes: Option<u32>,
pub distance_km: Option<f64>,
pub average_speed_kmh: Option<f64>,
pub max_speed_kmh: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TripDay {
pub date: Date,
pub totals: TripTotals,
pub trips: Vec<Trip>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Trip {
pub id: String,
pub started_at: Option<Timestamp>,
pub ended_at: Option<Timestamp>,
pub start: Option<Coordinates>,
pub end: Option<Coordinates>,
#[serde(rename = "_detail_ref")]
pub(crate) detail_ref: TripRef,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct TripRef {
pub service_tid: Value,
pub start: String,
pub end: String,
}
impl TripRef {
pub(crate) fn day(&self) -> &str {
self.start.get(..8).unwrap_or(&self.start)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TripDetail {
pub started_at: Option<Timestamp>,
pub ended_at: Option<Timestamp>,
pub totals: TripTotals,
pub hard_braking: Option<u32>,
pub rapid_acceleration: Option<u32>,
pub speeding: Option<u32>,
pub route: Vec<RoutePoint>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Coordinates {
pub latitude: f64,
pub longitude: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RoutePoint {
pub at: Option<Timestamp>,
pub latitude: f64,
pub longitude: f64,
}
#[derive(Debug, Default, Deserialize)]
struct WireTotals {
#[serde(rename = "tripDrvTime", default, deserialize_with = "flexible_int")]
drive_minutes: Option<u32>,
#[serde(rename = "tripIdleTime", default, deserialize_with = "flexible_int")]
idle_minutes: Option<u32>,
#[serde(rename = "tripDist", default, deserialize_with = "flexible_f64")]
distance_km: Option<f64>,
#[serde(rename = "tripAvgSpeed", default, deserialize_with = "flexible_f64")]
average_speed_kmh: Option<f64>,
#[serde(rename = "tripMaxSpeed", default, deserialize_with = "flexible_f64")]
max_speed_kmh: Option<f64>,
}
impl From<WireTotals> for TripTotals {
fn from(t: WireTotals) -> Self {
Self {
drive_minutes: t.drive_minutes,
idle_minutes: t.idle_minutes,
distance_km: t.distance_km,
average_speed_kmh: t.average_speed_kmh,
max_speed_kmh: t.max_speed_kmh,
}
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct WireTripMonth {
#[serde(flatten)]
totals: WireTotals,
#[serde(rename = "tripDayList", default, deserialize_with = "lenient_vec")]
days: Vec<WireTripDayCount>,
}
#[derive(Debug, Deserialize)]
struct WireTripDayCount {
#[serde(rename = "tripDayInMonth", deserialize_with = "yyyymmdd")]
date: Date,
#[serde(rename = "tripCntDay", default, deserialize_with = "flexible_int")]
trips: Option<u32>,
}
impl WireTripMonth {
pub(crate) fn into_month(self) -> TripMonth {
TripMonth {
totals: self.totals.into(),
days: self
.days
.into_iter()
.map(|d| TripDayCount {
date: d.date,
trips: d.trips.unwrap_or(0),
})
.collect(),
}
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct RawTripDayResponse {
#[serde(rename = "dayTripList", default, deserialize_with = "lenient_vec")]
day_trip_list: Vec<RawTripDay>,
}
#[derive(Debug, Deserialize)]
struct RawTripDay {
#[serde(flatten)]
totals: WireTotals,
#[serde(rename = "tripList", default, deserialize_with = "lenient_vec")]
trip_list: Vec<RawTrip>,
}
#[derive(Debug, Deserialize)]
struct RawTrip {
#[serde(rename = "serviceTID", deserialize_with = "present")]
service_tid: Value,
#[serde(rename = "tripStartTime", deserialize_with = "required_string")]
start: String,
#[serde(rename = "tripEndTime", default, deserialize_with = "flexible_string")]
end: Option<String>,
#[serde(rename = "tripStartCoord", default, deserialize_with = "lenient")]
start_coord: Option<RawCoord>,
#[serde(rename = "tripEndCoord", default, deserialize_with = "lenient")]
end_coord: Option<RawCoord>,
}
impl RawTrip {
fn into_trip(self) -> Trip {
let id = match &self.service_tid {
Value::String(s) => s.clone(),
other => other.to_string(),
};
let end = self.end.unwrap_or_default();
Trip {
id,
started_at: parse_ist(&self.start),
ended_at: parse_ist(&end),
start: self.start_coord.and_then(RawCoord::into_coordinates),
end: self.end_coord.and_then(RawCoord::into_coordinates),
detail_ref: TripRef {
service_tid: self.service_tid,
start: self.start,
end,
},
}
}
}
#[derive(Debug, Deserialize)]
struct RawCoord {
#[serde(default, deserialize_with = "flexible_f64")]
lat: Option<f64>,
#[serde(default, deserialize_with = "flexible_f64")]
lon: Option<f64>,
}
impl RawCoord {
fn into_coordinates(self) -> Option<Coordinates> {
Some(Coordinates {
latitude: self.lat?,
longitude: self.lon?,
})
}
}
impl RawTripDayResponse {
pub(crate) fn into_day(self, date: Date) -> TripDay {
let mut totals = TripTotals::default();
let mut trips = Vec::new();
for (i, day) in self.day_trip_list.into_iter().enumerate() {
if i == 0 {
totals = day.totals.into();
}
trips.extend(day.trip_list.into_iter().map(RawTrip::into_trip));
}
trips.sort_by(|a, b| a.detail_ref.start.cmp(&b.detail_ref.start));
TripDay {
date,
totals,
trips,
}
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct RawTripDetailResponse {
#[serde(rename = "tripInfo", default, deserialize_with = "lenient")]
trip_info: Option<RawTripDetail>,
}
#[derive(Debug, Default, Deserialize)]
struct RawTripDetail {
#[serde(flatten)]
totals: WireTotals,
#[serde(rename = "tripStartTime", default, deserialize_with = "ist_timestamp")]
started_at: Option<Timestamp>,
#[serde(rename = "tripEndTime", default, deserialize_with = "ist_timestamp")]
ended_at: Option<Timestamp>,
#[serde(
rename = "tripHardBreakingTime",
default,
deserialize_with = "flexible_int"
)]
hard_braking: Option<u32>,
#[serde(
rename = "tripRapidAccelationTime",
default,
deserialize_with = "flexible_int"
)]
rapid_acceleration: Option<u32>,
#[serde(
rename = "tripExcessiveSpeedTime",
default,
deserialize_with = "flexible_int"
)]
speeding: Option<u32>,
#[serde(rename = "tripList", default, deserialize_with = "lenient_vec")]
route: Vec<RawRoutePoint>,
}
#[derive(Debug, Deserialize)]
struct RawRoutePoint {
#[serde(default, deserialize_with = "flexible_f64")]
lat: Option<f64>,
#[serde(default, deserialize_with = "flexible_f64")]
lon: Option<f64>,
#[serde(rename = "tripDate", default, deserialize_with = "lenient")]
date: Option<RawUtc>,
}
#[derive(Debug, Deserialize)]
struct RawUtc {
#[serde(default, deserialize_with = "flexible_string")]
utc: Option<String>,
}
impl RawRoutePoint {
fn into_point(self) -> Option<RoutePoint> {
Some(RoutePoint {
at: self.date.and_then(|d| d.utc).as_deref().and_then(parse_utc),
latitude: self.lat?,
longitude: self.lon?,
})
}
}
impl RawTripDetailResponse {
pub(crate) fn into_detail(self) -> TripDetail {
let t = self.trip_info.unwrap_or_default();
TripDetail {
started_at: t.started_at,
ended_at: t.ended_at,
totals: t.totals.into(),
hard_braking: t.hard_braking,
rapid_acceleration: t.rapid_acceleration,
speeding: t.speeding,
route: t
.route
.into_iter()
.filter_map(RawRoutePoint::into_point)
.collect(),
}
}
}
fn yyyymmdd<'de, D: Deserializer<'de>>(d: D) -> Result<Date, D::Error> {
let raw = String::deserialize(d)?;
Date::strptime("%Y%m%d", &raw).map_err(serde::de::Error::custom)
}
fn present<'de, D: Deserializer<'de>>(d: D) -> Result<Value, D::Error> {
match Value::deserialize(d)? {
Value::Null => Err(serde::de::Error::custom("unexpected null")),
v => Ok(v),
}
}
fn required_string<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
flexible_string(d)?.ok_or_else(|| serde::de::Error::custom("expected a string"))
}