#![allow(dead_code)]
use crate::{
cache::{CacheError, Mod},
error::{AnkiError, AnkiResult},
model::FullModelDetails,
AnkiModules,
};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::{borrow::Borrow, hash::Hash, ops::Deref, sync::Arc};
use thiserror::Error;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ModelCache<K>
where
K: Hash + Eq,
{
#[serde(skip)]
modules: Mod,
cache: IndexMap<K, FullModelDetails>,
}
impl<K> ModelCache<K>
where
K: Hash + Eq,
{
pub fn new(modules: Arc<AnkiModules>) -> Self {
Self {
modules: modules.into(),
cache: IndexMap::new(),
}
}
}
impl ModelCache<String> {
pub async fn hydrate(&mut self) -> AnkiResult<&mut Self> {
let Some(modules) = &self.modules else {
return Err(AnkiError::Cache(CacheError::Dehydrated));
};
let latest: IndexMap<String, FullModelDetails> =
modules.models.get_all_models_full().await?;
self.cache = latest;
Ok(self)
}
}
impl<K> ModelCache<K>
where
K: Hash + Eq,
{
pub fn find_many_from_key_owned<'a, Q>(
&'a self,
keys: &'a [&Q],
) -> impl Iterator<Item = (K, FullModelDetails)> + 'a
where
K: Borrow<Q> + Clone,
Q: Hash + Eq + ?Sized,
{
keys.iter()
.filter_map(move |key| self.get_key_value(*key))
.map(|(k, v)| (k.clone(), v.clone()))
}
pub fn get_cache(&self) -> &IndexMap<K, FullModelDetails> {
&self.cache
}
}
impl<K> Deref for ModelCache<K>
where
K: Hash + Eq,
{
type Target = IndexMap<K, FullModelDetails>;
fn deref(&self) -> &Self::Target {
&self.cache
}
}
impl<T: Eq + Hash> From<ModelCache<T>> for IndexMap<T, FullModelDetails> {
fn from(val: ModelCache<T>) -> Self {
val.cache
}
}