use alloc::string::String;
use alloc::vec::Vec;
use core::fmt::Write;
use crate::calendar::{FiscalCalendar, Location};
use crate::date::Date;
use crate::error::Error;
use crate::json::{write_date, write_list, write_str};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DimensionRow {
pub location: Location,
pub labels: Vec<Option<String>>,
}
pub const FIXED_COLUMNS: [&str; 21] = [
"date",
"calendar_id",
"fiscal_year",
"quarter",
"period",
"week",
"day_of_year",
"day_of_quarter",
"day_of_period",
"day_of_week",
"year_start",
"year_last_day",
"quarter_start",
"quarter_last_day",
"period_start",
"period_last_day",
"week_start",
"week_last_day",
"year_has_extra_week",
"period_has_extra_week",
"week_is_extra_week",
];
enum Cell<'a> {
Text(&'a str),
Date(Date),
Int(i64),
Bool(bool),
Null,
}
impl Cell<'_> {
fn write_csv(&self, out: &mut String) {
match *self {
Cell::Text(s) => csv_field(out, s),
Cell::Date(d) => {
let _ = write!(out, "{d}");
}
Cell::Int(n) => {
let _ = write!(out, "{n}");
}
Cell::Bool(b) => out.push_str(if b { "true" } else { "false" }),
Cell::Null => {}
}
}
fn write_json(&self, out: &mut String) {
match *self {
Cell::Text(s) => write_str(out, s),
Cell::Date(d) => write_date(out, d),
Cell::Int(n) => {
let _ = write!(out, "{n}");
}
Cell::Bool(b) => out.push_str(if b { "true" } else { "false" }),
Cell::Null => out.push_str("null"),
}
}
}
impl FiscalCalendar {
pub fn dimension(&self, start: Date, end_exclusive: Date) -> Result<Vec<DimensionRow>, Error> {
let days = self.dimension_span(start, end_exclusive)?;
let mut rows = Vec::with_capacity(days as usize);
for d in 0..days {
let (fy, location) = self.locate_in(start.add(d), "start")?;
let labels = self
.label_slots()
.map(|(s, l)| self.label_for(s, l, &location, &fy))
.collect();
rows.push(DimensionRow { location, labels });
}
Ok(rows)
}
pub fn dimension_csv(&self, start: Date, end_exclusive: Date) -> Result<String, Error> {
let rows = self.dimension(start, end_exclusive)?;
let mut out = String::new();
write_list(&mut out, self.columns(), |out, name| csv_field(out, &name));
out.push('\n');
for row in &rows {
write_list(&mut out, self.cells(row), |out, cell| cell.write_csv(out));
out.push('\n');
}
Ok(out)
}
fn columns(&self) -> Vec<String> {
FIXED_COLUMNS
.iter()
.map(|c| String::from(*c))
.chain(self.label_columns())
.collect()
}
fn cells<'a>(&'a self, row: &'a DimensionRow) -> Vec<Cell<'a>> {
let l = &row.location;
let index = |i: Option<u32>| i.map_or(Cell::Null, |i| Cell::Int(i64::from(i)));
let mut cells = Vec::with_capacity(FIXED_COLUMNS.len() + row.labels.len());
cells.extend([
Cell::Date(l.date),
Cell::Text(self.calendar_id()),
Cell::Int(i64::from(l.year.year)),
index(l.quarter.index),
index(l.period.index),
index(l.week.index),
Cell::Int(i64::from(l.day_of_year)),
Cell::Int(i64::from(l.day_of_quarter)),
Cell::Int(i64::from(l.day_of_period)),
Cell::Int(i64::from(l.day_of_week)),
Cell::Date(l.year.start),
Cell::Date(l.year.last_day()),
Cell::Date(l.quarter.start),
Cell::Date(l.quarter.last_day()),
Cell::Date(l.period.start),
Cell::Date(l.period.last_day()),
Cell::Date(l.week.start),
Cell::Date(l.week.last_day()),
Cell::Bool(l.year.has_extra_week),
Cell::Bool(l.period.has_extra_week),
Cell::Bool(l.week.has_extra_week),
]);
cells.extend(
row.labels
.iter()
.map(|s| s.as_deref().map_or(Cell::Null, Cell::Text)),
);
cells
}
pub(crate) fn write_rows_json(&self, out: &mut String, rows: &[DimensionRow]) {
let names = self.columns();
out.push('[');
write_list(out, rows, |out, row| {
out.push('{');
write_list(
out,
names.iter().zip(self.cells(row)),
|out, (name, cell)| {
write_str(out, name);
out.push(':');
cell.write_json(out);
},
);
out.push('}');
});
out.push(']');
}
}
fn csv_field(out: &mut String, s: &str) {
if s.contains([',', '"', '\n', '\r']) {
out.push('"');
out.push_str(&s.replace('"', "\"\""));
out.push('"');
} else {
out.push_str(s);
}
}