use crate::error::GraphError;
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::sync::Arc;
use troupekit_agent::dsl::is_ident;
pub type ConditionFn =
Arc<dyn Fn(&Map<String, Value>, &[Value]) -> Result<String, String> + Send + Sync>;
#[derive(Clone)]
pub struct Conditions {
map: HashMap<String, ConditionFn>,
}
impl Default for Conditions {
fn default() -> Self {
Self::new()
}
}
impl Conditions {
pub fn new() -> Self {
let mut map: HashMap<String, ConditionFn> = HashMap::new();
map.insert("flag".into(), Arc::new(flag));
Self { map }
}
pub fn register(&mut self, name: &str, f: ConditionFn) -> Result<(), GraphError> {
if !is_ident(name) {
return Err(GraphError::Setup(format!(
"condition name `{name}` must match [a-z_][a-z0-9_]*"
)));
}
if self.map.contains_key(name) {
return Err(GraphError::Setup(format!(
"condition `{name}` is already registered"
)));
}
self.map.insert(name.to_string(), f);
Ok(())
}
pub fn get(&self, name: &str) -> Option<&ConditionFn> {
self.map.get(name)
}
}
fn flag(state: &Map<String, Value>, args: &[Value]) -> Result<String, String> {
let [Value::String(key)] = args else {
return Err("flag takes one state key".into());
};
match state.get(key) {
Some(Value::Bool(b)) => Ok(b.to_string()),
Some(_) => Err(format!("flag: `{key}` is not a bool")),
None => Err(format!("flag: `{key}` is not set")),
}
}