use super::*;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct NetMCard(NetMCardData);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetMCardData {
pub card: MCardRecord,
pub net_id: String,
pub places: Vec<PlaceMCard>,
pub transitions: Vec<TransitionMCard>,
pub marking: BTreeMap<String, Vec<TokenMCard>>,
#[serde(skip, default)]
cached_qualified_ref: MemoizedQualifiedRef,
}
impl std::ops::Deref for NetMCard {
type Target = NetMCardData;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<'de> Deserialize<'de> for NetMCard {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let model = Self(NetMCardData::deserialize(deserializer)?);
if model.verify() { Ok(model) } else { Err(serde::de::Error::custom("MCard view differs from its verified record")) }
}
}
impl NetMCard {
const KIND: &'static str = "net_mcard";
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(|token| token_models::reference_envelope(token, &token.card))
.collect::<Result<_, _>>()?;
marking_json.insert(pid.clone(), Value::Array(arr));
}
let places_json: Vec<Value> = places
.iter()
.map(|place| token_models::reference_envelope(place, &place.card))
.collect::<Result<_, _>>()?;
let trans_json: Vec<Value> = transitions
.iter()
.map(|transition| token_models::reference_envelope(transition, &transition.card))
.collect::<Result<_, _>>()?;
let envelope = json!({
"kind": Self::KIND,
"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(NetMCardData {
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).expect("immutable verified MCard"))
.to_string()
}
pub fn qualified_ref(&self) -> String {
self.qualified_hash()
}
pub fn verify(&self) -> bool {
let Ok(algorithm) = record_algorithm(&self.card) else { return false; };
Self::create(&self.net_id, self.places.clone(), self.transitions.clone(), self.marking.clone(), Some(&algorithm), None)
.is_ok_and(|rebuilt| rebuilt.card.content == self.card.content)
}
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, Self::KIND, &format!("net_tok_{}", self.net_id), Some(algo), timestamp)
}
}