use std::collections::HashMap;
use serde_json::Value;
use crate::extensions::FindGrowthBookAttribute;
use crate::model_public::{GrowthBookAttribute, GrowthBookAttributeValue};
pub type SavedGroups = HashMap<String, Vec<GrowthBookAttributeValue>>;
pub struct ConditionEvalContext<'a> {
attributes: &'a [GrowthBookAttribute],
saved_groups: &'a SavedGroups,
}
impl<'a> ConditionEvalContext<'a> {
pub fn new(
attributes: &'a [GrowthBookAttribute],
saved_groups: &'a SavedGroups,
) -> Self {
Self { attributes, saved_groups }
}
pub fn saved_group(
&self,
group_id: &str,
) -> Option<&[GrowthBookAttributeValue]> {
self.saved_groups.get(group_id).map(|members| members.as_slice())
}
}
impl FindGrowthBookAttribute for ConditionEvalContext<'_> {
fn find_value(
&self,
attribute_key: &str,
) -> Option<GrowthBookAttributeValue> {
self.attributes.find_value(attribute_key)
}
}
pub fn saved_groups_from_value(value: Option<&Value>) -> SavedGroups {
let mut groups = SavedGroups::new();
if let Some(Value::Object(map)) = value {
for (id, members) in map {
if let Value::Array(items) = members {
groups.insert(id.clone(), items.iter().map(|item| GrowthBookAttributeValue::from(item.clone())).collect());
}
}
}
groups
}