use super::*;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetMCard {
pub card: MCardRecord,
pub net_id: String,
pub places: Vec<PlaceMCard>,
pub transitions: Vec<TransitionMCard>,
pub marking: BTreeMap<String, Vec<TokenMCard>>,
#[serde(skip, default)]
pub cached_qualified_ref: MemoizedQualifiedRef,
}
impl NetMCard {
pub fn create(
net_id: &str,
places: Vec<PlaceMCard>,
transitions: Vec<TransitionMCard>,
marking: BTreeMap<String, Vec<TokenMCard>>,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Self, String> {
let mut marking_json = serde_json::Map::new();
for (pid, toks) in &marking {
let arr: Vec<Value> = toks
.iter()
.map(|t| json!({"color_type": t.color_type, "hash": t.card.hash, "payload": t.payload, "token_id": t.token_id}))
.collect();
marking_json.insert(pid.clone(), Value::Array(arr));
}
let places_json: Vec<Value> = places
.iter()
.map(|p| json!({"capacity": p.capacity, "hash": p.card.hash, "place_id": p.place_id, "role": p.role, "type_expr": p.type_expr}))
.collect();
let trans_json: Vec<Value> = transitions
.iter()
.map(|tr| json!({"codomain_type": tr.codomain_type, "coeffects": tr.coeffects, "domain_type": tr.domain_type, "hash": tr.card.hash, "input_places": tr.input_places, "operation_expr": tr.operation_expr, "output_places": tr.output_places, "transition_id": tr.transition_id}))
.collect();
let envelope = json!({
"kind": "net_mcard",
"marking": Value::Object(marking_json),
"net_id": net_id,
"places": places_json,
"transitions": trans_json,
});
let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
Ok(Self {
card,
net_id: net_id.to_string(),
places,
transitions,
marking,
cached_qualified_ref: MemoizedQualifiedRef::default(),
})
}
pub fn hash(&self) -> &str {
&self.card.hash
}
pub fn qualified_hash(&self) -> String {
self.cached_qualified_ref
.get_or_init(|| qualified_record_hash(&self.card))
.to_string()
}
pub fn qualified_ref(&self) -> String {
self.qualified_hash()
}
pub fn to_token_mcard(&self, algorithm: Option<&str>, timestamp: Option<&str>) -> Result<TokenMCard, String> {
let payload: Value = serde_json::from_slice(&self.card.content)
.map_err(|e| format!("Failed to decode NetMCard content: {e}"))?;
let algo_owned = record_algorithm(&self.card);
let algo = algorithm.unwrap_or(&algo_owned);
TokenMCard::from_payload(payload, "net_mcard", &format!("net_tok_{}", self.net_id), Some(algo), timestamp)
}
}