use std::collections::BTreeMap;
use serde_json::Value;
use super::{Declaration, ELECTION, Invalid, NAME, elections};
use crate::contract::Contract;
use crate::grammar::{IfaceId, KindToken};
pub const PROFILE: &str = "redundancy.v2";
#[must_use]
pub fn declaration<'a, U, R>(uses: U, resources: R, tokenless: bool) -> Declaration
where
U: IntoIterator<Item = &'a IfaceId>,
R: IntoIterator<Item = (&'a BTreeMap<String, Value>, bool)>,
{
let mut governed = false;
let mut another_major = false;
for u in uses {
if u.name() == NAME {
if u.major() == 2 {
governed = true;
} else {
another_major = true;
}
}
}
let resources: Vec<(Option<&Value>, bool)> = resources
.into_iter()
.map(|(a, explicit)| (a.get(ELECTION), explicit))
.collect();
let values: Vec<Option<&Value>> = resources.iter().map(|(v, _)| *v).collect();
if !governed && (another_major || values.iter().all(Option::is_none)) {
return Declaration::NotGoverned;
}
let mut why = Vec::new();
if governed && another_major {
why.push(Invalid::Majors);
}
if !governed {
why.push(Invalid::NotUsed);
}
let election = elections(&values, &mut why);
if governed && tokenless {
why.push(Invalid::Tokenless);
}
if governed && resources.iter().any(|(_, explicit)| *explicit) {
why.push(Invalid::ExplicitStream);
}
if why.is_empty() {
Declaration::Governed(election)
} else {
Declaration::Invalid(why)
}
}
#[must_use]
pub fn declaration_of(c: &Contract, tokenless: bool) -> Declaration {
declaration(
&c.uses,
c.resources
.iter()
.map(|r| (&r.annotations, r.token == KindToken::ExplicitStream)),
tokenless,
)
}