use core::fmt;
use openehr_mapping_core::header::metadata::MappingName;
use crate::engine::fhir::FhirKind;
use crate::model::ast::keyword::DataType;
use crate::model::ast::keyword::Direction;
use crate::resolve::program::binding::ResourceType;
use crate::resolve::program::condition::Condition;
use crate::resolve::program::condition::render_condition;
use crate::resolve::program::hierarchy::Create;
use crate::resolve::program::hierarchy::Preprocessor;
use crate::resolve::program::manual::Manual;
use crate::resolve::program::manual::render_manual;
use crate::resolve::program::port::Port;
use crate::resolve::program::port::render_ports;
use crate::resolve::program::target::FhirTarget;
use crate::resolve::program::target::OpenehrTarget;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkSide {
Reference,
String,
Resource,
}
impl LinkSide {
#[must_use]
pub fn of(target: &FhirTarget, depth: usize) -> Option<Self> {
match FhirKind::at(target.resolved().location()) {
Some(FhirKind::Reference) => Some(Self::Reference),
Some(FhirKind::String) => Some(Self::String),
_ if target.resolved().moves().is_empty() && depth > 0 && target.level() == depth => {
Some(Self::Resource)
}
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Method {
Value,
Slot {
model: MappingName,
preprocessors: Vec<Preprocessor>,
mappings: Vec<Mapping>,
},
SlotContext {
context: MappingName,
model: MappingName,
preprocessors: Vec<Preprocessor>,
mappings: Vec<Mapping>,
},
Reference {
resource: ResourceType,
mappings: Vec<Mapping>,
},
Link {
meaning: Option<String>,
link_type: Option<String>,
},
Programmed {
code: String,
ports: Vec<Port>,
},
Participation {
function: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Alternative {
code: &'static str,
target: FhirTarget,
}
impl Alternative {
#[must_use]
pub const fn new(code: &'static str, target: FhirTarget) -> Self {
Self { code, target }
}
#[must_use]
pub const fn code(&self) -> &'static str {
self.code
}
#[must_use]
pub const fn target(&self) -> &FhirTarget {
&self.target
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Derived {
Element(&'static str),
Choice {
read: FhirTarget,
write: Option<Alternative>,
},
Anchor,
Value {
code: &'static str,
target: OpenehrTarget,
},
Polymorphic {
read: FhirTarget,
pairings: Vec<Pairing>,
},
Declared(Alternative),
Event(Box<EventTime>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventTime {
read: FhirTarget,
time: OpenehrTarget,
point: Option<FhirTarget>,
interval: Option<FhirTarget>,
}
impl EventTime {
#[must_use]
pub const fn new(
read: FhirTarget,
time: OpenehrTarget,
point: Option<FhirTarget>,
interval: Option<FhirTarget>,
) -> Self {
Self {
read,
time,
point,
interval,
}
}
#[must_use]
pub const fn read(&self) -> &FhirTarget {
&self.read
}
#[must_use]
pub const fn time(&self) -> &OpenehrTarget {
&self.time
}
#[must_use]
pub const fn point(&self) -> Option<&FhirTarget> {
self.point.as_ref()
}
#[must_use]
pub const fn interval(&self) -> Option<&FhirTarget> {
self.interval.as_ref()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pairing {
alternative: Alternative,
suffix: &'static str,
rank: usize,
target: OpenehrTarget,
}
impl Pairing {
#[must_use]
pub const fn new(
alternative: Alternative,
suffix: &'static str,
rank: usize,
target: OpenehrTarget,
) -> Self {
Self {
alternative,
suffix,
rank,
target,
}
}
#[must_use]
pub const fn alternative(&self) -> &Alternative {
&self.alternative
}
#[must_use]
pub const fn suffix(&self) -> &'static str {
self.suffix
}
#[must_use]
pub const fn rank(&self) -> usize {
self.rank
}
#[must_use]
pub const fn target(&self) -> &OpenehrTarget {
&self.target
}
}
impl fmt::Display for Derived {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Element(code) => write!(f, "{code}"),
Self::Choice {
ref read,
ref write,
} => {
write!(f, "choice read {read}")?;
if let Some(written) = write.as_ref() {
write!(f, " write {} as {}", written.code, written.target)?;
}
Ok(())
}
Self::Anchor => f.write_str("anchor"),
Self::Value { code, ref target } => {
write!(f, "{code} into {}", target.node().rm_type())
}
Self::Declared(ref written) => {
write!(f, "{} as {}", written.code, written.target)
}
Self::Polymorphic {
ref read,
ref pairings,
} => {
write!(f, "choice read {read}")?;
for pairing in pairings {
write!(
f,
" {} into {}",
pairing.alternative.code,
pairing.target.node().rm_type()
)?;
}
Ok(())
}
Self::Event(ref event) => {
write!(f, "event time read {} into {}", event.read, event.time)?;
if let Some(ref point) = event.point {
write!(f, " point as {point}")?;
}
if let Some(ref interval) = event.interval {
write!(f, " interval as {interval}")?;
}
Ok(())
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mapping {
name: String,
model: MappingName,
fhir: Option<FhirTarget>,
openehr: Option<OpenehrTarget>,
data_type: Option<DataType>,
derived: Option<Derived>,
value: Option<String>,
direction: Option<Direction>,
fhir_condition: Option<Condition>,
openehr_condition: Option<Condition>,
manual: Vec<Manual>,
conceptmap: Option<String>,
method: Method,
followed_by: Vec<Mapping>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MappingParts {
pub name: String,
pub model: MappingName,
pub fhir: Option<FhirTarget>,
pub openehr: Option<OpenehrTarget>,
pub data_type: Option<DataType>,
pub derived: Option<Derived>,
pub value: Option<String>,
pub direction: Option<Direction>,
pub fhir_condition: Option<Condition>,
pub openehr_condition: Option<Condition>,
pub manual: Vec<Manual>,
pub conceptmap: Option<String>,
pub method: Method,
pub followed_by: Vec<Mapping>,
}
impl Mapping {
#[must_use]
pub fn new(parts: MappingParts) -> Self {
Self {
name: parts.name,
model: parts.model,
fhir: parts.fhir,
openehr: parts.openehr,
data_type: parts.data_type,
derived: parts.derived,
value: parts.value,
direction: parts.direction,
fhir_condition: parts.fhir_condition,
openehr_condition: parts.openehr_condition,
manual: parts.manual,
conceptmap: parts.conceptmap,
method: parts.method,
followed_by: parts.followed_by,
}
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub const fn model(&self) -> &MappingName {
&self.model
}
#[must_use]
pub const fn fhir(&self) -> Option<&FhirTarget> {
self.fhir.as_ref()
}
#[must_use]
pub const fn openehr(&self) -> Option<&OpenehrTarget> {
self.openehr.as_ref()
}
#[must_use]
pub const fn data_type(&self) -> Option<DataType> {
self.data_type
}
#[must_use]
pub const fn derived(&self) -> Option<&Derived> {
self.derived.as_ref()
}
#[must_use]
pub fn value(&self) -> Option<&str> {
self.value.as_deref()
}
#[must_use]
pub const fn direction(&self) -> Option<Direction> {
self.direction
}
#[must_use]
pub const fn fhir_condition(&self) -> Option<&Condition> {
self.fhir_condition.as_ref()
}
#[must_use]
pub const fn openehr_condition(&self) -> Option<&Condition> {
self.openehr_condition.as_ref()
}
#[must_use]
pub fn manual(&self) -> &[Manual] {
&self.manual
}
#[must_use]
pub fn conceptmap(&self) -> Option<&str> {
self.conceptmap.as_deref()
}
#[must_use]
pub const fn method(&self) -> &Method {
&self.method
}
#[must_use]
pub fn followed_by(&self) -> &[Mapping] {
&self.followed_by
}
pub(super) fn render(&self, f: &mut fmt::Formatter<'_>, depth: usize) -> fmt::Result {
let pad = " ".repeat(depth);
writeln!(f, "{pad}mapping {} from {}", self.name, self.model)?;
let inner = " ".repeat(depth.saturating_add(1));
if let Some(ref fhir) = self.fhir {
writeln!(f, "{inner}fhir {fhir}")?;
}
if let Some(ref openehr) = self.openehr {
writeln!(f, "{inner}openehr {openehr}")?;
}
if let Some(data_type) = self.data_type {
writeln!(f, "{inner}type {data_type}")?;
}
if let Some(ref derived) = self.derived {
writeln!(f, "{inner}derived {derived}")?;
}
if let Some(ref value) = self.value {
writeln!(f, "{inner}value {value}")?;
}
if let Some(direction) = self.direction {
writeln!(f, "{inner}unidirectional {direction}")?;
}
if let Some(ref conceptmap) = self.conceptmap {
writeln!(f, "{inner}conceptmap {conceptmap}")?;
}
for (label, condition) in [
("fhirCondition", self.fhir_condition.as_ref()),
("openehrCondition", self.openehr_condition.as_ref()),
] {
if let Some(condition) = condition {
render_condition(f, &inner, label, condition)?;
}
}
for manual in &self.manual {
render_manual(f, &inner, manual)?;
}
match self.method {
Method::Value => {}
Method::Slot {
ref model,
ref preprocessors,
ref mappings,
} => {
writeln!(f, "{inner}slotArchetype {model}")?;
let under = " ".repeat(depth.saturating_add(2));
for preprocessor in preprocessors {
render_preprocessor(f, &under, preprocessor)?;
}
for mapping in mappings {
mapping.render(f, depth.saturating_add(2))?;
}
}
Method::SlotContext {
ref context,
ref model,
ref preprocessors,
ref mappings,
} => {
writeln!(f, "{inner}slotContext {context} start {model}")?;
let under = " ".repeat(depth.saturating_add(2));
for preprocessor in preprocessors {
render_preprocessor(f, &under, preprocessor)?;
}
for mapping in mappings {
mapping.render(f, depth.saturating_add(2))?;
}
}
Method::Reference {
ref resource,
ref mappings,
} => {
writeln!(f, "{inner}reference {resource}")?;
for mapping in mappings {
mapping.render(f, depth.saturating_add(2))?;
}
}
Method::Link {
ref meaning,
ref link_type,
} => {
writeln!(
f,
"{inner}link meaning {} type {}",
meaning.as_deref().unwrap_or("-"),
link_type.as_deref().unwrap_or("-")
)?;
}
Method::Programmed {
ref code,
ref ports,
} => writeln!(f, "{inner}mappingCode {code}{}", render_ports(ports))?,
Method::Participation { ref function } => {
writeln!(f, "{inner}participationsFunction {function}")?;
}
}
for child in &self.followed_by {
child.render(f, depth.saturating_add(1))?;
}
Ok(())
}
}
pub(super) fn render_preprocessor(
f: &mut fmt::Formatter<'_>,
pad: &str,
preprocessor: &Preprocessor,
) -> fmt::Result {
if preprocessor.is_empty() {
return Ok(());
}
writeln!(f, "{pad}preprocessor {}", preprocessor.model())?;
let inner = format!("{pad} ");
for (label, condition) in [
("fhirCondition", preprocessor.fhir_condition()),
("openehrCondition", preprocessor.openehr_condition()),
] {
if let Some(condition) = condition {
render_condition(f, &inner, label, condition)?;
}
}
if let Some(hierarchy) = preprocessor.hierarchy() {
writeln!(f, "{inner}hierarchy")?;
if let Some(fhir) = hierarchy.fhir() {
writeln!(f, "{inner} fhir {fhir}")?;
}
if let Some(openehr) = hierarchy.openehr() {
writeln!(f, "{inner} openehr {openehr}")?;
}
for (label, split) in [
("split fhir", hierarchy.split_fhir()),
("split openehr", hierarchy.split_openehr()),
] {
let Some(split) = split else {
continue;
};
writeln!(
f,
"{inner} {label} create {}",
split.create().map_or("-", Create::as_str)
)?;
if let Some(path) = split.path() {
writeln!(f, "{inner} path {path}")?;
}
for unique in split.unique() {
writeln!(f, "{inner} unique {unique}")?;
}
}
}
Ok(())
}