001package org.hl7.fhir.r5.elementmodel;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r5
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023
024import java.util.ArrayList;
025import java.util.List;
026
027import org.hl7.fhir.exceptions.DefinitionException;
028import org.hl7.fhir.exceptions.FHIRException;
029import org.hl7.fhir.r5.conformance.ProfileUtilities;
030import org.hl7.fhir.r5.context.IWorkerContext;
031import org.hl7.fhir.r5.formats.FormatUtilities;
032import org.hl7.fhir.r5.model.ElementDefinition;
033import org.hl7.fhir.r5.model.ElementDefinition.PropertyRepresentation;
034import org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent;
035import org.hl7.fhir.r5.model.StructureDefinition;
036import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind;
037import org.hl7.fhir.r5.model.TypeDetails;
038import org.hl7.fhir.r5.utils.ToolingExtensions;
039import org.hl7.fhir.r5.utils.TypesUtilities;
040import org.hl7.fhir.utilities.Utilities;
041
042public class Property {
043
044        private IWorkerContext context;
045        private ElementDefinition definition;
046        private StructureDefinition structure;
047        private Boolean canBePrimitive; 
048
049        public Property(IWorkerContext context, ElementDefinition definition, StructureDefinition structure) {
050                this.context = context;
051                this.definition = definition;
052                this.structure = structure;
053        }
054
055        public String getName() {
056                return definition.getPath().substring(definition.getPath().lastIndexOf(".")+1);
057        }
058
059        public ElementDefinition getDefinition() {
060                return definition;
061        }
062
063        public String getType() {
064                if (definition.getType().size() == 0)
065                        return null;
066                else if (definition.getType().size() > 1) {
067                        String tn = definition.getType().get(0).getWorkingCode();
068                        for (int i = 1; i < definition.getType().size(); i++) {
069                                if (!tn.equals(definition.getType().get(i).getWorkingCode()))
070                                        throw new Error("logic error, gettype when types > 1");
071                        }
072                        return tn;
073                } else
074                        return definition.getType().get(0).getWorkingCode();
075        }
076
077        public String getType(String elementName) {
078    if (!definition.getPath().contains("."))
079      return definition.getPath();
080    ElementDefinition ed = definition;
081    if (definition.hasContentReference()) {
082      if (!definition.getContentReference().startsWith("#"))
083        throw new Error("not handled yet");
084      boolean found = false;
085      for (ElementDefinition d : structure.getSnapshot().getElement()) {
086        if (d.hasId() && d.getId().equals(definition.getContentReference().substring(1))) {
087          found = true;
088          ed = d;
089        }
090      }
091      if (!found)
092        throw new Error("Unable to resolve "+definition.getContentReference()+" at "+definition.getPath()+" on "+structure.getUrl());
093    }
094    if (ed.getType().size() == 0)
095                        return null;
096    else if (ed.getType().size() > 1) {
097      String t = ed.getType().get(0).getCode();
098                        boolean all = true;
099      for (TypeRefComponent tr : ed.getType()) {
100                                if (!t.equals(tr.getCode()))
101                                        all = false;
102                        }
103                        if (all)
104                                return t;
105      String tail = ed.getPath().substring(ed.getPath().lastIndexOf(".")+1);
106      if (tail.endsWith("[x]") && elementName != null && elementName.startsWith(tail.substring(0, tail.length()-3))) {
107                                String name = elementName.substring(tail.length()-3);
108        return isPrimitive(lowFirst(name)) ? lowFirst(name) : name;        
109                        } else {
110              if (ToolingExtensions.hasExtension(ed, "http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype"))
111                return ToolingExtensions.readStringExtension(ed, "http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");
112        throw new Error("logic error, gettype when types > 1, name mismatch for "+elementName+" on at "+ed.getPath());
113                        }
114    } else if (ed.getType().get(0).getCode() == null) {
115      if (Utilities.existsInList(ed.getId(), "Element.id", "Extension.url"))
116        return "string";
117      else
118        return structure.getId();
119                } else
120      return ed.getType().get(0).getWorkingCode();
121        }
122
123  public boolean hasType(String elementName) {
124    if (definition.getType().size() == 0)
125      return false;
126    else if (definition.getType().size() > 1) {
127      String t = definition.getType().get(0).getCode();
128      boolean all = true;
129      for (TypeRefComponent tr : definition.getType()) {
130        if (!t.equals(tr.getCode()))
131          all = false;
132      }
133      if (all)
134        return true;
135      String tail = definition.getPath().substring(definition.getPath().lastIndexOf(".")+1);
136      if (tail.endsWith("[x]") && elementName.startsWith(tail.substring(0, tail.length()-3))) {
137        String name = elementName.substring(tail.length()-3);
138        return true;        
139      } else
140        return false;
141    } else
142      return true;
143  }
144
145        public StructureDefinition getStructure() {
146                return structure;
147        }
148
149        /**
150         * Is the given name a primitive
151         * 
152         * @param E.g. "Observation.status"
153         */
154        public boolean isPrimitiveName(String name) {
155          String code = getType(name);
156      return isPrimitive(code);
157        }
158
159        /**
160         * Is the given type a primitive
161         * 
162         * @param E.g. "integer"
163         */
164        public boolean isPrimitive(String code) {
165          return TypesUtilities.isPrimitive(code);
166         // was this... but this can be very inefficient compared to hard coding the list
167//              StructureDefinition sd = context.fetchTypeDefinition(code);
168//      return sd != null && sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE;
169        }
170
171        private String lowFirst(String t) {
172                return t.substring(0, 1).toLowerCase()+t.substring(1);
173        }
174
175        public boolean isResource() {
176          if (definition.getType().size() > 0)
177            return definition.getType().size() == 1 && ("Resource".equals(definition.getType().get(0).getCode()) || "DomainResource".equals(definition.getType().get(0).getCode()));
178          else
179            return !definition.getPath().contains(".") && (structure.getKind() == StructureDefinitionKind.RESOURCE || structure.getKind() == StructureDefinitionKind.LOGICAL);
180        }
181
182        public boolean isList() {
183          return !"1".equals(definition.getMax());
184        }
185
186  public String getScopedPropertyName() {
187    return definition.getBase().getPath();
188  }
189
190  public String getNamespace() {
191    if (ToolingExtensions.hasExtension(definition, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace"))
192      return ToolingExtensions.readStringExtension(definition, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace");
193    if (ToolingExtensions.hasExtension(structure, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace"))
194      return ToolingExtensions.readStringExtension(structure, "http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace");
195    return FormatUtilities.FHIR_NS;
196  }
197
198  private boolean isElementWithOnlyExtension(final ElementDefinition ed, final List<ElementDefinition> children) {
199    boolean result = false;
200    if (!ed.getType().isEmpty()) {
201      result = true;
202      for (final ElementDefinition ele : children) {
203        if (!ele.getPath().contains("extension")) {
204          result = false;
205          break;
206        }
207      }
208    }
209    return result;
210  }
211  
212        public boolean IsLogicalAndHasPrimitiveValue(String name) {
213//              if (canBePrimitive!= null)
214//                      return canBePrimitive;
215                
216                canBePrimitive = false;
217        if (structure.getKind() != StructureDefinitionKind.LOGICAL)
218                return false;
219        if (!hasType(name))
220                return false;
221        StructureDefinition sd = context.fetchResource(StructureDefinition.class, structure.getUrl().substring(0, structure.getUrl().lastIndexOf("/")+1)+getType(name));
222        if (sd == null)
223          sd = context.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(getType(name), context.getOverrideVersionNs()));
224    if (sd != null && sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE)
225      return true;
226        if (sd == null || sd.getKind() != StructureDefinitionKind.LOGICAL)
227                return false;
228        for (ElementDefinition ed : sd.getSnapshot().getElement()) {
229                if (ed.getPath().equals(sd.getId()+".value") && ed.getType().size() == 1 && isPrimitive(ed.getType().get(0).getCode())) {
230                        canBePrimitive = true;
231                        return true;
232                }
233        }
234        return false;
235        }
236
237  public boolean isChoice() {
238    if (definition.getType().size() <= 1)
239      return false;
240    String tn = definition.getType().get(0).getCode();
241    for (int i = 1; i < definition.getType().size(); i++) 
242      if (!definition.getType().get(i).getCode().equals(tn))
243        return true;
244    return false;
245  }
246
247
248  protected List<Property> getChildProperties(String elementName, String statedType) throws FHIRException {
249    ElementDefinition ed = definition;
250    StructureDefinition sd = structure;
251    List<ElementDefinition> children = ProfileUtilities.getChildMap(sd, ed);
252    String url = null;
253    if (children.isEmpty() || isElementWithOnlyExtension(ed, children)) {
254      // ok, find the right definitions
255      String t = null;
256      if (ed.getType().size() == 1)
257        t = ed.getType().get(0).getWorkingCode();
258      else if (ed.getType().size() == 0)
259        throw new Error("types == 0, and no children found on "+getDefinition().getPath());
260      else {
261        t = ed.getType().get(0).getWorkingCode();
262        boolean all = true;
263        for (TypeRefComponent tr : ed.getType()) {
264          if (!tr.getWorkingCode().equals(t)) {
265            all = false;
266            break;
267          }
268        }
269        if (!all) {
270          // ok, it's polymorphic
271          if (ed.hasRepresentation(PropertyRepresentation.TYPEATTR)) {
272            t = statedType;
273            if (t == null && ToolingExtensions.hasExtension(ed, "http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype"))
274              t = ToolingExtensions.readStringExtension(ed, "http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");
275            boolean ok = false;
276            for (TypeRefComponent tr : ed.getType()) { 
277              if (tr.getWorkingCode().equals(t)) 
278                ok = true;
279              if (Utilities.isAbsoluteUrl(tr.getWorkingCode())) {
280                StructureDefinition sdt = context.fetchResource(StructureDefinition.class, tr.getWorkingCode());
281                if (sdt != null && sdt.getType().equals(t)) {
282                  url = tr.getWorkingCode();
283                  ok = true;
284                }
285              }
286              if (ok)
287                break;
288            }
289             if (!ok)
290               throw new DefinitionException("Type '"+t+"' is not an acceptable type for '"+elementName+"' on property "+definition.getPath());
291            
292          } else {
293            t = elementName.substring(tail(ed.getPath()).length() - 3);
294            if (isPrimitive(lowFirst(t)))
295              t = lowFirst(t);
296          }
297        }
298      }
299      if (!"xhtml".equals(t)) {
300        for (TypeRefComponent aType: ed.getType()) {
301          if (aType.getWorkingCode().equals(t)) {
302            if (aType.hasProfile()) {
303              assert aType.getProfile().size() == 1; 
304              url = aType.getProfile().get(0).getValue();
305            } else {
306              url = ProfileUtilities.sdNs(t, context.getOverrideVersionNs());
307            }
308            break;
309          }
310        }
311        if (url==null)
312          throw new FHIRException("Unable to find type " + t + " for element " + elementName + " with path " + ed.getPath());
313        sd = context.fetchResource(StructureDefinition.class, url);        
314        if (sd == null)
315          throw new DefinitionException("Unable to find type '"+t+"' for name '"+elementName+"' on property "+definition.getPath());
316        children = ProfileUtilities.getChildMap(sd, sd.getSnapshot().getElement().get(0));
317      }
318    }
319    List<Property> properties = new ArrayList<Property>();
320    for (ElementDefinition child : children) {
321      properties.add(new Property(context, child, sd));
322    }
323    return properties;
324  }
325
326  protected List<Property> getChildProperties(TypeDetails type) throws DefinitionException {
327    ElementDefinition ed = definition;
328    StructureDefinition sd = structure;
329    List<ElementDefinition> children = ProfileUtilities.getChildMap(sd, ed);
330    if (children.isEmpty()) {
331      // ok, find the right definitions
332      String t = null;
333      if (ed.getType().size() == 1)
334        t = ed.getType().get(0).getCode();
335      else if (ed.getType().size() == 0)
336        throw new Error("types == 0, and no children found");
337      else {
338        t = ed.getType().get(0).getCode();
339        boolean all = true;
340        for (TypeRefComponent tr : ed.getType()) {
341          if (!tr.getCode().equals(t)) {
342            all = false;
343            break;
344          }
345        }
346        if (!all) {
347          // ok, it's polymorphic
348          t = type.getType();
349        }
350      }
351      if (!"xhtml".equals(t)) {
352        sd = context.fetchResource(StructureDefinition.class, t);
353        if (sd == null)
354          throw new DefinitionException("Unable to find class '"+t+"' for name '"+ed.getPath()+"' on property "+definition.getPath());
355        children = ProfileUtilities.getChildMap(sd, sd.getSnapshot().getElement().get(0));
356      }
357    }
358    List<Property> properties = new ArrayList<Property>();
359    for (ElementDefinition child : children) {
360      properties.add(new Property(context, child, sd));
361    }
362    return properties;
363  }
364
365  private String tail(String path) {
366    return path.contains(".") ? path.substring(path.lastIndexOf(".")+1) : path;
367  }
368
369  public Property getChild(String elementName, String childName) throws FHIRException {
370    List<Property> children = getChildProperties(elementName, null);
371    for (Property p : children) {
372      if (p.getName().equals(childName)) {
373        return p;
374      }
375    }
376    return null;
377  }
378
379  public Property getChild(String name, TypeDetails type) throws DefinitionException {
380    List<Property> children = getChildProperties(type);
381    for (Property p : children) {
382      if (p.getName().equals(name) || p.getName().equals(name+"[x]")) {
383        return p;
384      }
385    }
386    return null;
387  }
388
389  public Property getChild(String name) throws FHIRException {
390    List<Property> children = getChildProperties(name, null);
391    for (Property p : children) {
392      if (p.getName().equals(name)) {
393        return p;
394      }
395    }
396    return null;
397  }
398
399  public Property getChildSimpleName(String elementName, String name) throws FHIRException {
400    List<Property> children = getChildProperties(elementName, null);
401    for (Property p : children) {
402      if (p.getName().equals(name) || p.getName().equals(name+"[x]")) {
403        return p;
404      }
405    }
406    return null;
407  }
408
409  public IWorkerContext getContext() {
410    return context;
411  }
412
413  @Override
414  public String toString() {
415    return definition.getPath();
416  }
417
418
419}