use std::time::{Duration, SystemTime};
use crate::{
BundledNetwork, Error, GlobalId, LegEnd, LocalTime, Location, Network, Timestamp, Trip,
};
type UtcTime = Timestamp;
uniffi::custom_type!(UtcTime, SystemTime, {
lower: |time| {
let seconds = Duration::from_secs(time.unix_seconds.unsigned_abs());
let epoch = SystemTime::UNIX_EPOCH;
if time.unix_seconds >= 0 {
epoch.checked_add(seconds)
} else {
epoch.checked_sub(seconds)
}
.unwrap_or(epoch)
},
try_lift: |time| {
let seconds = match time.duration_since(SystemTime::UNIX_EPOCH) {
Ok(after) => i64::try_from(after.as_secs())?,
Err(before) => {
let before = before.duration();
-i64::try_from(before.as_secs())? - i64::from(before.subsec_nanos() > 0)
}
};
Ok(Timestamp { unix_seconds: seconds })
},
});
uniffi::custom_type!(LocalTime, String, {
lower: |time| time.iso_8601(),
try_lift: |_text| {
uniffi::deps::anyhow::bail!("nothing takes a local time")
},
});
#[uniffi::export]
impl BundledNetwork {
#[uniffi::method(name = "id")]
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "UniFFI hands a method its receiver by reference"
)]
fn ffi_id(&self) -> String {
self.id().to_owned()
}
#[uniffi::method(name = "network")]
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "UniFFI hands a method its receiver by reference"
)]
fn ffi_network(&self) -> Network {
self.network()
}
}
#[uniffi::export]
impl Location {
#[uniffi::method(name = "station_ids")]
fn ffi_station_ids(&self) -> Vec<GlobalId> {
self.station_ids()
}
#[uniffi::method(name = "same_station")]
fn ffi_same_station(&self, other: &Self) -> bool {
self.same_station(other)
}
#[uniffi::method(name = "local_time")]
fn ffi_local_time(&self, time: UtcTime) -> Option<LocalTime> {
self.local_time(time)
}
}
#[uniffi::export]
impl Trip {
#[uniffi::method(name = "departure")]
fn ffi_departure(&self) -> Option<LegEnd> {
self.departure().cloned()
}
#[uniffi::method(name = "arrival")]
fn ffi_arrival(&self) -> Option<LegEnd> {
self.arrival().cloned()
}
#[uniffi::method(name = "transfers")]
fn ffi_transfers(&self) -> u32 {
u32::try_from(self.transfers()).unwrap_or(u32::MAX)
}
}
#[uniffi::export]
fn network_from_json(id: &str, json: &str) -> Result<Network, Error> {
Network::from_json(id, json)
}