use super::{
get_context_value, ConditionBlock, ConditionContext, ConditionOperator, ConditionValue,
};
use serde_json::Value;
use std::collections::HashMap;
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConditionError {
UnknownOperator(String),
TypeMismatch {
expected: String,
actual: String,
},
InvalidBooleanValue,
InvalidDate {
error: String,
},
MissingContextKey(String),
InvalidConditionStructure(String),
InvalidConditionValue {
operator: String,
key: String,
position: Option<usize>,
expected: String,
},
OperatorWithoutKey {
operator: String,
},
OperatorKeyMismatch {
operator: String,
key: String,
key_type: String,
},
}
impl std::fmt::Display for ConditionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConditionError::UnknownOperator(op) => write!(f, "Unknown operator: {}", op),
ConditionError::TypeMismatch { expected, actual } => {
write!(f, "Type mismatch: expected {}, got {}", expected, actual)
}
ConditionError::InvalidBooleanValue => {
write!(f, "Invalid boolean value: must be 'true' or 'false'")
}
ConditionError::InvalidDate { error } => {
write!(f, "Invalid date value: {error}")
}
ConditionError::MissingContextKey(key) => {
write!(f, "Missing context key: {}", key)
}
ConditionError::InvalidConditionStructure(msg) => {
write!(f, "Invalid condition structure: {}", msg)
}
ConditionError::InvalidConditionValue {
operator,
key,
position,
expected,
} => {
write!(f, "Invalid value for {operator} on key {key}")?;
if let Some(index) = position {
write!(f, " at element {index}")?;
}
write!(f, ": expected {expected}")
}
ConditionError::OperatorWithoutKey { operator } => write!(
f,
"{operator} cannot be used: no key of that kind holds a list"
),
ConditionError::OperatorKeyMismatch {
operator,
key,
key_type,
} => write!(
f,
"{operator} cannot compare key {key}, which is {key_type}"
),
}
}
}
impl std::error::Error for ConditionError {}
impl From<ConditionError> for crate::error::AmiError {
fn from(err: ConditionError) -> Self {
crate::error::AmiError::InvalidParameter {
message: err.to_string(),
}
}
}
pub fn evaluate_condition_block(
block: &ConditionBlock,
context: &ConditionContext,
) -> Result<bool, ConditionError> {
let mut operators: Vec<_> = block.iter().collect();
operators.sort_by_key(|(name, _)| *name);
let mut holds = true;
for (operator_name, key_value_map) in operators {
let operator = ConditionOperator::from_str(operator_name)?;
holds &= evaluate_operator_block(operator, key_value_map, context)?;
}
Ok(holds)
}
fn evaluate_operator_block(
operator: ConditionOperator,
key_value_map: &HashMap<String, ConditionValue>,
context: &ConditionContext,
) -> Result<bool, ConditionError> {
let mut keys: Vec<_> = key_value_map.iter().collect();
keys.sort_by_key(|(key, _)| *key);
let mut holds = true;
for (key, expected_value) in keys {
let actual_value = get_context_value(key, context)
.map_err(|e| ConditionError::MissingContextKey(format!("{}: {}", key, e)))?;
holds &= super::operators::evaluate_operator(operator, actual_value, expected_value)?;
}
Ok(holds)
}
pub fn parse_condition_block(value: &Value) -> Result<ConditionBlock, ConditionError> {
let obj = value.as_object().ok_or_else(|| {
ConditionError::InvalidConditionStructure("Condition must be an object".to_string())
})?;
let mut block = ConditionBlock::new();
for (operator_name, key_value_obj) in obj {
let operator = ConditionOperator::from_str(operator_name)?;
let key_value_map = key_value_obj.as_object().ok_or_else(|| {
ConditionError::InvalidConditionStructure(format!(
"Operator '{}' value must be an object",
operator_name
))
})?;
let mut key_values = HashMap::new();
for (key, value) in key_value_map {
crate::validate::check_value(operator_name, operator, key, value)?;
let condition_value = ConditionValue::from(value.clone());
key_values.insert(key.clone(), condition_value);
}
block.insert(operator_name.clone(), key_values);
}
Ok(block)
}