use super::NumberOptions;
use super::data::{self, DATE_REL, DATE_REL_PARTS, Loc};
use crate::plural::{self, Operands};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct RelativeOptions {
auto: bool,
style: u8,
}
impl RelativeOptions {
#[must_use]
pub const fn auto(mut self) -> Self {
self.auto = true;
self
}
#[must_use]
pub const fn short(mut self) -> Self {
self.style = 1;
self
}
#[must_use]
pub const fn narrow(mut self) -> Self {
self.style = 2;
self
}
}
const SPANS: [f64; 6] = [31_536_000.0, 2_592_000.0, 86_400.0, 3600.0, 60.0, 1.0];
#[allow(
clippy::cast_precision_loss,
reason = "JS subtracts the two as doubles"
)]
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a whole count"
)]
pub(crate) fn write(
at: i64,
now: i64,
o: RelativeOptions,
loc: &Loc,
out: &mut dyn fmt::Write,
) -> fmt::Result {
let seconds = (at as f64 - now as f64) / 1000.0;
let size = seconds.abs();
let unit = SPANS
.iter()
.position(|&s| size >= s)
.unwrap_or(SPANS.len() - 1);
let n = (size / SPANS.get(unit).copied().unwrap_or(1.0)).floor();
let past = seconds < 0.0;
let part = DATE_REL
.get(usize::from(loc.drel))
.and_then(|r| r.get(unit * 3 + usize::from(o.style)))
.and_then(|&p| DATE_REL_PARTS.get(usize::from(p)));
let s = |i: usize| data::dname(part.and_then(|r| r.get(i)).copied().unwrap_or(0));
if o.auto && n <= 2.0 {
let word = s(if past { 2 - n as usize } else { 2 + n as usize });
if !word.is_empty() {
return out.write_str(word);
}
}
let cat = plural::select_rule(loc.plural, &Operands::int(n as u64)) as usize;
let list = if past { 11 } else { 5 };
let pattern = match s(list + cat) {
"" => s(list + 5),
p => p,
};
let Some((before, after)) = pattern.split_once("{0}") else {
return out.write_str(pattern);
};
out.write_str(before)?;
super::number::write(n, &NumberOptions::DEFAULT, loc, out)?;
out.write_str(after)
}