1use std::collections::BTreeSet;
30
31use ifc_model::{Edit, EntityId, Model, Transaction, Value};
32
33use super::check_relate;
34use super::owned_relationships::refs;
35use super::release::{bind, projected_type, stage, Release};
36use super::{invalid, SpatialAuthoringError, SpatialAuthoringResult};
37use crate::relation::slots::SERVICES_BUILDINGS;
38
39const ENTITY: &str = SERVICES_BUILDINGS.type_name;
40
41pub fn serve_buildings(
63 tx: &mut Transaction,
64 model: &Model,
65 global_id: &str,
66 system: EntityId,
67 buildings: &[EntityId],
68) -> SpatialAuthoringResult<EntityId> {
69 serve(tx, model, global_id, system, buildings, None)
70}
71
72pub fn serve_buildings_with_owner_history(
83 tx: &mut Transaction,
84 model: &Model,
85 global_id: &str,
86 system: EntityId,
87 buildings: &[EntityId],
88 owner_history: EntityId,
89) -> SpatialAuthoringResult<EntityId> {
90 serve(tx, model, global_id, system, buildings, Some(owner_history))
91}
92
93fn serve(
94 tx: &mut Transaction,
95 model: &Model,
96 global_id: &str,
97 system: EntityId,
98 buildings: &[EntityId],
99 owner_history: Option<EntityId>,
100) -> SpatialAuthoringResult<EntityId> {
101 let release = bind(model)?;
102 check_relate(SERVICES_BUILDINGS, global_id, system, buildings)?;
103 let mut seen = BTreeSet::new();
104 if let Some(repeated) = buildings.iter().find(|id| !seen.insert(**id)) {
105 return Err(invalid(
106 ENTITY,
107 "RelatedBuildings",
108 format!("#{} repeats in a SET", repeated.0),
109 ));
110 }
111 require(release, tx, model, "RelatingSystem", system)?;
112 for &building in buildings {
113 require(release, tx, model, "RelatedBuildings", building)?;
114 }
115 if let Some(existing) = services_of(tx, model, system) {
116 return Err(invalid(
117 ENTITY,
118 "RelatingSystem",
119 format!(
120 "#{} already services buildings through #{}",
121 system.0, existing.0
122 ),
123 ));
124 }
125 let values = vec![
126 ("GlobalId", Value::Text(global_id.into())),
127 ("RelatingSystem", Value::Ref(system)),
128 ("RelatedBuildings", refs(buildings)),
129 ];
130 stage(tx, model, ENTITY, values, owner_history)
131}
132
133fn require(
136 release: Release,
137 tx: &Transaction,
138 model: &Model,
139 attribute: &'static str,
140 target: EntityId,
141) -> SpatialAuthoringResult<()> {
142 let actual = projected_type(tx, model, target)
143 .ok_or(SpatialAuthoringError::MissingReference {
144 entity: ENTITY,
145 attribute,
146 target,
147 })?
148 .to_ascii_uppercase();
149 let schema = release.schema();
150 let declared = schema
151 .attributes(ENTITY)
152 .iter()
153 .find(|a| a.name.eq_ignore_ascii_case(attribute))
154 .map(|a| a.type_name.as_str())
155 .ok_or(SpatialAuthoringError::EntityNotInSchema {
156 entity: ENTITY,
157 schema: release.version(),
158 })?;
159 if schema.accepts_type(declared, &actual) {
160 Ok(())
161 } else {
162 Err(SpatialAuthoringError::WrongReferenceType {
163 entity: ENTITY,
164 attribute,
165 target,
166 actual,
167 expected: declared,
168 })
169 }
170}
171
172fn services_of(tx: &Transaction, model: &Model, system: EntityId) -> Option<EntityId> {
175 let staged = tx.edits().iter().filter_map(|edit| match edit {
176 Edit::Create { id, .. } => Some(*id),
177 _ => None,
178 });
179 let mut candidates: Vec<EntityId> = model.ids_of_type(ENTITY).to_vec();
180 candidates.extend(staged);
181 candidates.sort_unstable();
182 candidates.dedup();
183 candidates.into_iter().find(|&id| {
184 projected_type(tx, model, id).is_some_and(|t| t.eq_ignore_ascii_case(ENTITY))
185 && projected_system(tx, model, id) == Some(system)
186 })
187}
188
189fn projected_system(tx: &Transaction, model: &Model, id: EntityId) -> Option<EntityId> {
191 let slot = SERVICES_BUILDINGS.relating;
192 for edit in tx.edits().iter().rev() {
193 match edit {
194 Edit::Remove { id: removed } if *removed == id => return None,
195 Edit::SetAttribute {
196 id: edited,
197 slot: at,
198 value,
199 } if *edited == id && *at == slot => {
200 return match value {
201 Value::Ref(system) => Some(*system),
202 _ => None,
203 }
204 }
205 Edit::Create {
206 id: created,
207 entity,
208 } if *created == id => {
209 return match entity.attributes.get(slot) {
210 Some(Value::Ref(system)) => Some(*system),
211 _ => None,
212 }
213 }
214 _ => {}
215 }
216 }
217 match model.get(id)?.attributes.get(slot)? {
218 Value::Ref(system) => Some(*system),
219 _ => None,
220 }
221}