use super::*;
use serde_json;
pub type PropertyConverter<P> = fn(src: &str) -> Result<Vec<Arc<P>>>;
pub fn rule_json_array_parser<P: SentinelRule + DeserializeOwned>(
src: &str,
) -> Result<Vec<Arc<P>>> {
println!("{:?}", src);
println!("{:?}", serde_json::from_str::<Vec<P>>(src));
let rules: Vec<P> = serde_json::from_str(src)?;
Ok(rules.into_iter().map(|r| Arc::new(r)).collect())
}
pub type PropertyUpdater<P> = fn(rule: Vec<Arc<P>>) -> Result<bool>;
pub trait PropertyHandler<P: SentinelRule>: Send + Sync {
fn is_property_consistent(&mut self, rules: &Vec<Arc<P>>) -> bool;
fn handle(&mut self, src: Option<&String>) -> Result<bool>;
fn load(&mut self, rules: Vec<Arc<P>>) -> Result<bool>;
}
pub struct DefaultPropertyHandler<P: SentinelRule + PartialEq + DeserializeOwned> {
last_update_property: Option<Vec<Arc<P>>>,
converter: PropertyConverter<P>,
updater: PropertyUpdater<P>,
}
impl<P: SentinelRule + PartialEq + DeserializeOwned> DefaultPropertyHandler<P> {
pub fn new(converter: PropertyConverter<P>, updater: PropertyUpdater<P>) -> Arc<Self> {
Arc::new(Self {
converter,
updater,
last_update_property: None,
})
}
}
impl<P: SentinelRule + PartialEq + DeserializeOwned> PropertyHandler<P>
for DefaultPropertyHandler<P>
{
fn is_property_consistent<'a>(&mut self, rules: &'a Vec<Arc<P>>) -> bool {
if self.last_update_property.is_some()
&& &self.last_update_property.as_ref().unwrap() == &rules
{
true
} else {
self.last_update_property = Some(rules.clone());
false
}
}
fn handle(&mut self, src: Option<&String>) -> Result<bool> {
match src {
Some(src) => {
let rules = (self.converter)(src)?;
let is_the_same = self.is_property_consistent(&rules);
if is_the_same {
return Ok(false);
}
(self.updater)(rules)
}
None => (self.updater)(Vec::new()),
}
}
fn load(&mut self, rules: Vec<Arc<P>>) -> Result<bool> {
(self.updater)(rules)
}
}