use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::cpn::mcard_token::{
qualified_record_hash, record_from_canonical_json, DEFAULT_TIMESTAMP,
};
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct MCardMarking {
pub by_place: BTreeMap<String, Vec<String>>,
}
impl<'de> Deserialize<'de> for MCardMarking {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum MarkingHelper {
Wrapped { by_place: BTreeMap<String, Vec<String>> },
Transparent(BTreeMap<String, Vec<String>>),
}
let helper = MarkingHelper::deserialize(deserializer)?;
match helper {
MarkingHelper::Wrapped { by_place } => Ok(MCardMarking { by_place }),
MarkingHelper::Transparent(by_place) => Ok(MCardMarking { by_place }),
}
}
}
impl MCardMarking {
pub fn new() -> Self {
Self { by_place: BTreeMap::new() }
}
pub fn with_token(mut self, place_id: &str, token_ref: &str) -> Self {
self.append(place_id, token_ref.to_string());
self
}
pub fn restrict(&self, place_ids: &BTreeSet<String>) -> Self {
let mut by_place = BTreeMap::new();
for pid in place_ids {
if let Some(vals) = self.by_place.get(pid) {
by_place.insert(pid.clone(), vals.clone());
}
}
Self { by_place }
}
pub fn tokens(&self) -> &BTreeMap<String, Vec<String>> {
&self.by_place
}
pub fn place_refs(&self, place_id: &str) -> Vec<String> {
self.by_place.get(place_id).cloned().unwrap_or_default()
}
pub fn tokens_at(&self, place_id: &str) -> Vec<String> {
self.place_refs(place_id)
}
pub fn count(&self, place_id: &str) -> usize {
self.by_place.get(place_id).map(|v| v.len()).unwrap_or(0)
}
pub fn token_counts(&self) -> BTreeMap<String, usize> {
self.by_place.iter().map(|(k, v)| (k.clone(), v.len())).collect()
}
pub fn append(&mut self, place_id: &str, qualified_ref: String) {
self.by_place.entry(place_id.to_string()).or_default().push(qualified_ref);
}
pub fn pop_first(&mut self, place_id: &str) -> Option<String> {
let vec = self.by_place.get_mut(place_id)?;
if vec.is_empty() { None } else { Some(vec.remove(0)) }
}
pub fn state_hash(&self, algorithm: Option<&str>) -> Result<String, String> {
let val = serde_json::to_value(&self.by_place)
.map_err(|e| format!("Failed to serialize MCardMarking: {e}"))?;
let rec = record_from_canonical_json(&val, algorithm, Some(DEFAULT_TIMESTAMP))?;
Ok(qualified_record_hash(&rec))
}
}