use std::fmt;
use crate::export::Export;
use crate::import::Import;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SheetKey {
Index(usize),
Name(String),
}
impl fmt::Display for SheetKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Index(index) => write!(f, "{index}"),
Self::Name(name) => f.write_str(name),
}
}
}
impl From<usize> for SheetKey {
fn from(index: usize) -> Self {
Self::Index(index)
}
}
impl From<&str> for SheetKey {
fn from(name: &str) -> Self {
Self::Name(name.to_owned())
}
}
impl From<String> for SheetKey {
fn from(name: String) -> Self {
Self::Name(name)
}
}
pub trait IntoSheet {
fn into_sheet(self) -> Sheet;
}
pub enum Sheet {
Export(Box<dyn Export>),
Import(Box<dyn Import>),
}
#[derive(Default)]
pub struct Sheets {
entries: Vec<(SheetKey, Sheet)>,
}
impl Sheets {
pub fn new() -> Self {
Self::default()
}
pub fn sheet(mut self, sheet: impl IntoSheet) -> Self {
let next = self
.entries
.iter()
.filter_map(|(key, _)| match key {
SheetKey::Index(index) => Some(index + 1),
SheetKey::Name(_) => None,
})
.max()
.unwrap_or(0);
self.entries.push((SheetKey::Index(next), sheet.into_sheet()));
self
}
pub fn named(mut self, name: impl Into<String>, sheet: impl IntoSheet) -> Self {
self.entries.push((SheetKey::Name(name.into()), sheet.into_sheet()));
self
}
pub fn at(mut self, index: usize, sheet: impl IntoSheet) -> Self {
self.entries.push((SheetKey::Index(index), sheet.into_sheet()));
self
}
pub fn only<K: Into<SheetKey>>(mut self, keys: impl IntoIterator<Item = K>) -> Self {
let keys: Vec<SheetKey> = keys.into_iter().map(Into::into).collect();
self.entries.retain(|(key, _)| keys.contains(key));
self
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn into_entries(self) -> Vec<(SheetKey, Sheet)> {
self.entries
}
pub(crate) fn exports(self) -> Vec<Box<dyn Export>> {
self.entries
.into_iter()
.filter_map(|(_, sheet)| match sheet {
Sheet::Export(export) => Some(export),
Sheet::Import(_) => None,
})
.collect()
}
pub(crate) fn imports(self) -> Vec<(SheetKey, Box<dyn Import>)> {
self.entries
.into_iter()
.filter_map(|(key, sheet)| match sheet {
Sheet::Import(import) => Some((key, import)),
Sheet::Export(_) => None,
})
.collect()
}
}