use fhir_types::codec::Value;
use crate::model::ast::keyword::ConditionOperator;
use crate::model::ast::keyword::Direction;
use crate::resolve::program::condition::Condition;
use crate::tree::Occurrence;
use crate::tree::element::Location;
use crate::tree::element::Table;
use crate::tree::error::ReadError;
use crate::tree::path::FhirPath;
use crate::tree::read::Match;
use crate::tree::read::Selected;
use crate::tree::read::read;
#[must_use]
pub const fn runs(condition: &Condition, direction: Direction) -> bool {
matches!(
(condition.direction(), direction),
(Direction::FhirToOpenehr, Direction::FhirToOpenehr)
| (Direction::OpenehrToFhir, Direction::OpenehrToFhir)
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
Gate(bool),
Filter(Vec<Occurrence>),
}
impl Verdict {
#[must_use]
pub fn admits_any(&self) -> bool {
match *self {
Self::Gate(passed) => passed,
Self::Filter(ref occurrences) => !occurrences.is_empty(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ConditionError {
#[error("the condition on {target} could not be read")]
Read {
target: String,
#[source]
source: ReadError,
},
#[error("the condition on the openEHR side cannot be read over a FHIR document")]
WrongSide,
#[error("the {operator} operator needs a target attribute, and the condition names none")]
NoAttribute {
operator: ConditionOperator,
},
}
pub fn evaluate<T: Table + ?Sized>(
table: &T,
document: &Value,
condition: &Condition,
attached: bool,
) -> Result<Verdict, ConditionError> {
let root = fhir_target(condition.target())?;
let attributes = attribute_paths(condition)?;
if !attached {
let whole = Occurrence::default();
return Ok(Verdict::Gate(holds(
table,
document,
condition,
&attributes,
&whole,
)));
}
let admitted = matches_of(table, document, root)?
.into_iter()
.filter(|occurrence| holds(table, document, condition, &attributes, occurrence))
.collect();
Ok(Verdict::Filter(admitted))
}
fn fhir_target(
target: &crate::resolve::program::target::Target,
) -> Result<&FhirPath, ConditionError> {
match *target {
crate::resolve::program::target::Target::Fhir(ref target) => Ok(target.expression()),
crate::resolve::program::target::Target::Openehr(_) => Err(ConditionError::WrongSide),
}
}
fn attribute_paths(condition: &Condition) -> Result<Vec<&FhirPath>, ConditionError> {
let mut paths = Vec::with_capacity(condition.attributes().len());
for attribute in condition.attributes() {
paths.push(fhir_target(attribute)?);
}
if paths.is_empty() && condition.operator() != ConditionOperator::Type {
return Err(ConditionError::NoAttribute {
operator: condition.operator(),
});
}
Ok(paths)
}
fn matches_of<T: Table + ?Sized>(
table: &T,
document: &Value,
path: &FhirPath,
) -> Result<Vec<Occurrence>, ConditionError> {
Ok(read_path(table, document, path)?
.into_iter()
.map(|matched| matched.occurrence().clone())
.collect())
}
fn read_path<'tree, T: Table + ?Sized>(
table: &T,
document: &'tree Value,
path: &FhirPath,
) -> Result<Vec<Match<'tree>>, ConditionError> {
read(table, document, path).map_err(|source| ConditionError::Read {
target: String::from(path.as_str()),
source,
})
}
fn holds<T: Table + ?Sized>(
table: &T,
document: &Value,
condition: &Condition,
attributes: &[&FhirPath],
root: &Occurrence,
) -> bool {
let mut found = attribute_values(table, document, attributes, root);
if condition.operator() == ConditionOperator::Type {
found.types = type_names(table, document, condition, attributes, root);
}
decide(condition, &found)
}
#[must_use]
pub fn decide(condition: &Condition, found: &Attributes) -> bool {
match condition.operator() {
ConditionOperator::OneOf => found
.values
.iter()
.any(|value| condition.criteria().iter().any(|wanted| wanted == value)),
ConditionOperator::NotOf => found
.values
.iter()
.all(|value| condition.criteria().iter().all(|wanted| wanted != value)),
ConditionOperator::Empty => found.present == 0,
ConditionOperator::NotEmpty => found.present > 0,
ConditionOperator::Type => found
.types
.iter()
.any(|named| condition.criteria().iter().any(|wanted| wanted == named)),
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Attributes {
pub present: usize,
pub values: Vec<String>,
pub types: Vec<String>,
}
fn attribute_values<T: Table + ?Sized>(
table: &T,
document: &Value,
attributes: &[&FhirPath],
root: &Occurrence,
) -> Attributes {
let mut found = Attributes::default();
for path in attributes {
let Ok(matches) = read(table, document, path) else {
continue;
};
for matched in matches {
if !under(matched.occurrence(), root) {
continue;
}
found.present = found.present.saturating_add(1);
if let Selected::Value(value) = *matched.selected()
&& let Some(text) = scalar(value)
{
found.values.push(text);
}
}
}
found
}
fn type_names<T: Table + ?Sized>(
table: &T,
document: &Value,
condition: &Condition,
attributes: &[&FhirPath],
root: &Occurrence,
) -> Vec<String> {
let mut paths: Vec<&FhirPath> = attributes.to_vec();
if paths.is_empty()
&& let Ok(target) = fhir_target(condition.target())
{
paths.push(target);
}
let mut names = Vec::new();
for path in paths {
let Some(resource) = document.get("resourceType").and_then(Value::as_str) else {
continue;
};
let Ok(resolved) = crate::tree::element::resolve(table, resource, path) else {
continue;
};
let Ok(matches) = read(table, document, path) else {
continue;
};
if !matches
.iter()
.any(|matched| under(matched.occurrence(), root))
{
continue;
}
if let Some(name) = type_name(resolved.location()) {
names.push(String::from(name));
}
}
names
}
const fn type_name(location: &Location) -> Option<&'static str> {
match *location {
Location::Complex(schema) => Some(schema.path),
Location::Primitive(_)
| Location::Attribute
| Location::PrimitiveElement
| Location::Choice(_)
| Location::Resource
| Location::Deferred => None,
}
}
fn under(occurrence: &Occurrence, root: &Occurrence) -> bool {
occurrence.indices().starts_with(root.indices())
}
fn scalar(value: &Value) -> Option<String> {
match *value {
Value::String(ref text) => Some(text.clone()),
Value::Bool(flag) => Some(String::from(if flag { "true" } else { "false" })),
Value::Number(ref number) => Some(String::from(number.as_str())),
Value::Null | Value::Array(_) | Value::Object(_) => None,
}
}