use derivative::Derivative;
use crate::{
error::{Error, ErrorValue, Result},
file::File,
};
pub trait Resource: Send + Sync + 'static {
fn version(&self, path: &str) -> Result<String>;
fn file(&self, path: &str) -> Result<Vec<u8>>;
}
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Ironworks {
#[derivative(Debug = "ignore")]
resources: Vec<Box<dyn Resource>>,
}
impl Default for Ironworks {
fn default() -> Self {
Self::new()
}
}
impl Ironworks {
pub fn new() -> Self {
Self {
resources: Default::default(),
}
}
pub fn add_resource(&mut self, resource: impl Resource) {
self.resources.push(Box::new(resource));
}
#[must_use]
pub fn with_resource(mut self, resource: impl Resource) -> Self {
self.resources.push(Box::new(resource));
self
}
pub fn version(&self, path: &str) -> Result<String> {
self.find_first(path, |resource| resource.version(path))
}
pub fn file<F: File>(&self, path: &str) -> Result<F> {
let data = self.find_first(path, |resource| resource.file(path))?;
F::read(data)
}
fn find_first<F, O>(&self, path: &str, f: F) -> Result<O>
where
F: Fn(&Box<dyn Resource>) -> Result<O>,
{
self.resources
.iter()
.rev()
.map(f)
.find(|result| !matches!(result, Err(Error::NotFound(ErrorValue::Path(_)))))
.unwrap_or_else(|| Err(Error::NotFound(ErrorValue::Path(path.into()))))
}
}