1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//! Resource definitions.

#[rustfmt::skip] // Too much for rustfmt
mod generated;

pub use generated::*;

use super::types::{FieldExtension, Identifier};

/// Trait for all resources with multiple identifiers in the `identifier` field.
/// Simplifies access to identifiers.
pub trait IdentifiableResource {
	/// Get the identifier field.
	fn identifier(&self) -> &Vec<Option<Identifier>>;
	/// Get the identifier field mutably.
	fn identifier_mut(&mut self) -> &mut Vec<Option<Identifier>>;
	/// Set the identifier field.
	fn set_identifier(&mut self, value: Vec<Option<Identifier>>);

	/// Get the identifier extension field.
	fn identifier_ext(&self) -> &Vec<Option<FieldExtension>>;
	/// Get the identifier extension field mutably.
	fn identifier_ext_mut(&mut self) -> &mut Vec<Option<FieldExtension>>;
	/// Set the identifier extension field.
	fn set_identifier_ext(&mut self, value: Vec<Option<FieldExtension>>);

	/// Append or replace an identifier. If there is already an identifier with
	/// the same system or type (exact full match), it is replaced, otherwise
	/// appended.
	///
	/// Returns whether it was created (true) or replaced another identifier
	/// (false).
	fn place_identifier(&mut self, identifier: Identifier) -> bool {
		if let Some(ident) = self.identifier_mut().iter_mut().flatten().find(|ident| {
			(ident.system.is_some() && ident.system == identifier.system)
				|| (ident.r#type.is_some() && ident.r#type == identifier.r#type)
		}) {
			*ident = identifier;

			false
		} else {
			self.identifier_mut().push(Some(identifier));

			if !self.identifier_ext_mut().is_empty()
				&& self.identifier_mut().len() == self.identifier_ext_mut().len() + 1
			{
				self.identifier_ext_mut().push(None);
			}

			true
		}
	}

	/// Return the first identifier value for a given system.
	fn identifier_with_system(&self, system: &str) -> Option<&String> {
		self.identifier()
			.iter()
			.flatten()
			.filter(|ident| ident.system.as_ref().map_or(false, |sys| sys == system))
			.find_map(|ident| ident.value.as_ref())
	}

	/// Return a list of identifiers for a given system.
	fn identifiers_with_system(&self, system: &str) -> Vec<&Identifier> {
		self.identifier()
			.iter()
			.flatten()
			.filter(|ident| ident.system.as_ref().map_or(false, |sys| sys == system))
			.collect()
	}

	/// Return the first identifier value for a given type.
	fn identifier_with_type(&self, type_system: &str, type_code: &str) -> Option<&String> {
		self.identifier()
			.iter()
			.flatten()
			.filter(|ident| {
				ident.r#type.as_ref().map_or(false, |ty| {
					ty.coding.iter().flatten().any(|coding| {
						coding.system.as_deref() == Some(type_system)
							&& coding.code.as_deref() == Some(type_code)
					})
				})
			})
			.find_map(|ident| ident.value.as_ref())
	}

	/// Return a list of identifiers for a given type.
	fn identifiers_with_type(&self, type_system: &str, type_code: &str) -> Vec<&Identifier> {
		self.identifier()
			.iter()
			.flatten()
			.filter(|ident| {
				ident.r#type.as_ref().map_or(false, |ty| {
					ty.coding.iter().flatten().any(|coding| {
						coding.system.as_deref() == Some(type_system)
							&& coding.code.as_deref() == Some(type_code)
					})
				})
			})
			.collect()
	}
}

/// Implement the IdentifiableResource trait for the resources and the resource
/// enum.
macro_rules! impl_identifiable_resource {
	([$($resource:ident),*$(,)?]) => {
		$(impl_identifiable_resource!($resource);)*

		impl Resource {
			/// Return the resource as identifiable resource.
			#[must_use]
			#[inline]
			pub fn as_identifiable_resource(&self) -> Option<&dyn IdentifiableResource> {
				match self {
					$(
						Self::$resource(r) => Some(r),
					)*
					_ => None,
				}
			}

			/// Return the resource as mutable identifiable resource.
			#[must_use]
			#[inline]
			pub fn as_identifiable_resource_mut(&mut self) -> Option<&mut dyn IdentifiableResource> {
				match self {
					$(
						Self::$resource(r) => Some(r),
					)*
					_ => None,
				}
			}
		}
	};
	($resource:ident) => {
		impl IdentifiableResource for $resource {
			#[inline]
			fn identifier(&self) -> &Vec<Option<Identifier>> {
				&self.identifier
			}

			#[inline]
			fn identifier_mut(&mut self) -> &mut Vec<Option<Identifier>> {
				&mut self.identifier
			}

			#[inline]
			fn set_identifier(&mut self, value: Vec<Option<Identifier>>) {
				self.identifier = value;
			}

			#[inline]
			fn identifier_ext(&self) -> &Vec<Option<FieldExtension>> {
				&self.identifier_ext
			}

			#[inline]
			fn identifier_ext_mut(&mut self) -> &mut Vec<Option<FieldExtension>> {
				&mut self.identifier_ext
			}

			#[inline]
			fn set_identifier_ext(&mut self, value: Vec<Option<FieldExtension>>) {
				self.identifier_ext = value;
			}
		}
	};
}

impl_identifiable_resource!([
	Account,
	ActivityDefinition,
	ActorDefinition,
	AdministrableProductDefinition,
	AdverseEvent,
	AllergyIntolerance,
	Appointment,
	AppointmentResponse,
	ArtifactAssessment,
	Basic,
	BiologicallyDerivedProduct,
	BiologicallyDerivedProductDispense,
	BodyStructure,
	CapabilityStatement,
	CarePlan,
	CareTeam,
	ChargeItem,
	ChargeItemDefinition,
	Citation,
	Claim,
	ClaimResponse,
	ClinicalImpression,
	ClinicalUseDefinition,
	CodeSystem,
	Communication,
	CommunicationRequest,
	Composition,
	ConceptMap,
	Condition,
	ConditionDefinition,
	Consent,
	Contract,
	Coverage,
	CoverageEligibilityRequest,
	CoverageEligibilityResponse,
	DetectedIssue,
	Device,
	DeviceAssociation,
	DeviceDefinition,
	DeviceDispense,
	DeviceMetric,
	DeviceRequest,
	DeviceUsage,
	DiagnosticReport,
	DocumentReference,
	Encounter,
	EncounterHistory,
	Endpoint,
	EnrollmentRequest,
	EnrollmentResponse,
	EpisodeOfCare,
	EventDefinition,
	Evidence,
	EvidenceReport,
	EvidenceVariable,
	ExampleScenario,
	ExplanationOfBenefit,
	FamilyMemberHistory,
	Flag,
	FormularyItem,
	GenomicStudy,
	Goal,
	GraphDefinition,
	Group,
	GuidanceResponse,
	HealthcareService,
	ImagingSelection,
	ImagingStudy,
	Immunization,
	ImmunizationEvaluation,
	ImmunizationRecommendation,
	ImplementationGuide,
	InsurancePlan,
	InventoryItem,
	InventoryReport,
	Invoice,
	Library,
	List,
	Location,
	ManufacturedItemDefinition,
	Measure,
	MeasureReport,
	Medication,
	MedicationAdministration,
	MedicationDispense,
	MedicationKnowledge,
	MedicationRequest,
	MedicationStatement,
	MedicinalProductDefinition,
	MessageDefinition,
	MolecularSequence,
	NamingSystem,
	NutritionIntake,
	NutritionOrder,
	Observation,
	OperationDefinition,
	Organization,
	OrganizationAffiliation,
	PackagedProductDefinition,
	Patient,
	PaymentNotice,
	PaymentReconciliation,
	Person,
	PlanDefinition,
	Practitioner,
	PractitionerRole,
	Procedure,
	Questionnaire,
	QuestionnaireResponse,
	RegulatedAuthorization,
	RelatedPerson,
	RequestOrchestration,
	Requirements,
	ResearchStudy,
	ResearchSubject,
	RiskAssessment,
	Schedule,
	SearchParameter,
	ServiceRequest,
	Slot,
	Specimen,
	StructureDefinition,
	StructureMap,
	Subscription,
	SubscriptionTopic,
	Substance,
	SubstanceDefinition,
	SupplyDelivery,
	SupplyRequest,
	Task,
	TerminologyCapabilities,
	TestPlan,
	TestScript,
	Transport,
	ValueSet,
	VisionPrescription
]);