001package org.hl7.fhir.r5.terminologies;
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.Calendar;
026import java.util.HashSet;
027import java.util.List;
028import java.util.Set;
029
030import org.hl7.fhir.exceptions.FHIRException;
031import org.hl7.fhir.exceptions.FHIRFormatError;
032import org.hl7.fhir.r5.model.BooleanType;
033import org.hl7.fhir.r5.model.CanonicalType;
034import org.hl7.fhir.r5.model.CodeSystem;
035import org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionComponent;
036import org.hl7.fhir.r5.model.CodeSystem.ConceptPropertyComponent;
037import org.hl7.fhir.r5.model.CodeSystem.PropertyComponent;
038import org.hl7.fhir.r5.model.CodeSystem.PropertyType;
039import org.hl7.fhir.r5.model.CodeType;
040import org.hl7.fhir.r5.model.DateTimeType;
041import org.hl7.fhir.r5.model.Enumerations.PublicationStatus;
042import org.hl7.fhir.r5.model.Identifier;
043import org.hl7.fhir.r5.model.Meta;
044import org.hl7.fhir.r5.model.DataType;
045import org.hl7.fhir.r5.model.UriType;
046import org.hl7.fhir.r5.utils.ToolingExtensions;
047import org.hl7.fhir.utilities.StandardsStatus;
048import org.hl7.fhir.utilities.Utilities;
049
050public class CodeSystemUtilities {
051
052  public static class CodeSystemNavigator {
053
054    private CodeSystem cs;
055    private boolean restructure;
056    private Set<String> processed = new HashSet<>();
057
058    public CodeSystemNavigator(CodeSystem cs) {
059      this.cs = cs;
060      restructure = hasExtraRelationships(cs.getConcept());
061    }
062
063    public boolean isRestructure() {
064      return restructure;
065    }
066
067    private boolean hasExtraRelationships(List<ConceptDefinitionComponent> concept) {
068      for (ConceptDefinitionComponent cd : concept) {
069        if (!getSubsumedBy(cd).isEmpty()) {
070          return true;
071        }
072        for (ConceptDefinitionComponent cdc : cd.getConcept()) {
073          if (hasExtraRelationships(cdc.getConcept())) {
074            return true;
075          }
076        }
077      }
078      return false;
079    }
080
081    public List<ConceptDefinitionComponent> getConcepts(ConceptDefinitionComponent context) {
082      if (context == null) {
083        if (restructure) {
084          List<ConceptDefinitionComponent> res = new ArrayList<>();
085          for (ConceptDefinitionComponent cd : cs.getConcept()) {
086            if (getSubsumedBy(cd).isEmpty()) {
087              res.add(cd);
088              processed.add(cd.getCode());
089            }
090          }
091          return res;
092        } else {
093          return cs.getConcept();
094        }
095      } else {
096        if (restructure) {
097          List<ConceptDefinitionComponent> res = new ArrayList<>();
098          for (ConceptDefinitionComponent cd : context.getConcept()) {
099            res.add(cd);
100            processed.add(cd.getCode());
101          }
102          for (ConceptDefinitionComponent cd : cs.getConcept()) {
103            if (getSubsumedBy(cd).contains(context.getCode()) && !processed.contains(cd.getCode())) {
104              res.add(cd);
105              processed.add(cd.getCode());
106            }
107          }
108          return res;
109        } else {
110          return context.getConcept();
111        }
112      }
113    }
114
115    private List<String> getSubsumedBy(ConceptDefinitionComponent cd) {
116      List<String> codes = new ArrayList<>();
117      for (ConceptPropertyComponent cp : cd.getProperty()) {
118        if (cp.getCode().equals("subsumedBy")) {
119          codes.add(cp.getValue().primitiveValue());
120        }
121      }
122      return codes;
123    }
124
125    public List<ConceptDefinitionComponent> getOtherChildren(ConceptDefinitionComponent context) {
126      List<ConceptDefinitionComponent> res = new ArrayList<>();
127      for (ConceptDefinitionComponent cd : cs.getConcept()) {
128        if (getSubsumedBy(cd).contains(context.getCode()) && processed.contains(cd.getCode())) {
129          res.add(cd);
130        }
131      }
132      return res;
133    }
134  }
135
136
137  public static boolean isNotSelectable(CodeSystem cs, ConceptDefinitionComponent def) {
138    for (ConceptPropertyComponent p : def.getProperty()) {
139      if (p.getCode().equals("notSelectable") && p.hasValue() && p.getValue() instanceof BooleanType) 
140        return ((BooleanType) p.getValue()).getValue();
141    }
142    return false;
143  }
144
145  public static void setNotSelectable(CodeSystem cs, ConceptDefinitionComponent concept) throws FHIRFormatError {
146    defineNotSelectableProperty(cs);
147    ConceptPropertyComponent p = getProperty(concept, "notSelectable");
148    if (p != null)
149      p.setValue(new BooleanType(true));
150    else
151      concept.addProperty().setCode("notSelectable").setValue(new BooleanType(true));    
152  }
153
154  public static void defineNotSelectableProperty(CodeSystem cs) {
155    defineCodeSystemProperty(cs, "notSelectable", "Indicates that the code is abstract - only intended to be used as a selector for other concepts", PropertyType.BOOLEAN);
156  }
157
158
159  public enum ConceptStatus {
160    Active, Experimental, Deprecated, Retired;
161
162    public String toCode() {
163      switch (this) {
164      case Active: return "active";
165      case Experimental: return "experimental";
166      case Deprecated: return "deprecated";
167      case Retired: return "retired";
168      default: return null;
169      }
170    }
171  }
172
173  public static void setStatus(CodeSystem cs, ConceptDefinitionComponent concept, ConceptStatus status) throws FHIRFormatError {
174    defineStatusProperty(cs);
175    ConceptPropertyComponent p = getProperty(concept, "status");
176    if (p != null)
177      p.setValue(new CodeType(status.toCode()));
178    else
179      concept.addProperty().setCode("status").setValue(new CodeType(status.toCode()));    
180  }
181
182  public static void defineStatusProperty(CodeSystem cs) {
183    defineCodeSystemProperty(cs, "status", "A property that indicates the status of the concept. One of active, experimental, deprecated, retired", PropertyType.CODE);
184  }
185
186  private static void defineDeprecatedProperty(CodeSystem cs) {
187    defineCodeSystemProperty(cs, "deprecationDate", "The date at which a concept was deprecated. Concepts that are deprecated but not inactive can still be used, but their use is discouraged", PropertyType.DATETIME);
188  }
189
190  public static void defineParentProperty(CodeSystem cs) {
191    defineCodeSystemProperty(cs, "parent", "The concept identified in this property is a parent of the concept on which it is a property. The property type will be 'code'. The meaning of parent/child relationships is defined by the hierarchyMeaning attribute", PropertyType.CODE);
192  }
193
194  public static void defineChildProperty(CodeSystem cs) {
195    defineCodeSystemProperty(cs, "child", "The concept identified in this property is a child of the concept on which it is a property. The property type will be 'code'. The meaning of parent/child relationships is defined by the hierarchyMeaning attribute", PropertyType.CODE);
196  }
197
198  public static boolean isDeprecated(CodeSystem cs, ConceptDefinitionComponent def)  {
199    try {
200      for (ConceptPropertyComponent p : def.getProperty()) {
201        if (p.getCode().equals("status") && p.hasValue() && p.hasValueCodeType() && p.getValueCodeType().getCode().equals("deprecated"))
202          return true;
203        // this, though status should also be set
204        if (p.getCode().equals("deprecationDate") && p.hasValue() && p.getValue() instanceof DateTimeType) 
205          return ((DateTimeType) p.getValue()).before(new DateTimeType(Calendar.getInstance()));
206        // legacy  
207        if (p.getCode().equals("deprecated") && p.hasValue() && p.getValue() instanceof BooleanType) 
208          return ((BooleanType) p.getValue()).getValue();
209      }
210      return false;
211    } catch (FHIRException e) {
212      return false;
213    }
214  }
215
216  public static void setDeprecated(CodeSystem cs, ConceptDefinitionComponent concept, DateTimeType date) throws FHIRFormatError {
217    setStatus(cs, concept, ConceptStatus.Deprecated);
218    defineDeprecatedProperty(cs);
219    concept.addProperty().setCode("deprecationDate").setValue(date);    
220  }
221  
222  public static boolean isInactive(CodeSystem cs, ConceptDefinitionComponent def) throws FHIRException {
223    for (ConceptPropertyComponent p : def.getProperty()) {
224      if (p.getCode().equals("status") && p.hasValueStringType()) 
225        return "inactive".equals(p.getValueStringType());
226    }
227    return false;
228  }
229  
230  public static boolean isInactive(CodeSystem cs, String code) throws FHIRException {
231    ConceptDefinitionComponent def = findCode(cs.getConcept(), code);
232    if (def == null)
233      return true;
234    return isInactive(cs, def);
235  }
236
237  public static void defineCodeSystemProperty(CodeSystem cs, String code, String description, PropertyType type) {
238    for (PropertyComponent p : cs.getProperty()) {
239      if (p.getCode().equals(code))
240        return;
241    }
242    cs.addProperty().setCode(code).setDescription(description).setType(type).setUri("http://hl7.org/fhir/concept-properties#"+code);
243  }
244
245  public static String getCodeDefinition(CodeSystem cs, String code) {
246    return getCodeDefinition(cs.getConcept(), code);
247  }
248
249  private static String getCodeDefinition(List<ConceptDefinitionComponent> list, String code) {
250    for (ConceptDefinitionComponent c : list) {
251      if (c.hasCode() &&  c.getCode().equals(code))
252        return c.getDefinition();
253      String s = getCodeDefinition(c.getConcept(), code);
254      if (s != null)
255        return s;
256    }
257    return null;
258  }
259
260  public static CodeSystem makeShareable(CodeSystem cs) {
261    if (!cs.hasMeta())
262      cs.setMeta(new Meta());
263    for (UriType t : cs.getMeta().getProfile()) 
264      if (t.getValue().equals("http://hl7.org/fhir/StructureDefinition/shareablecodesystem"))
265        return cs;
266    cs.getMeta().getProfile().add(new CanonicalType("http://hl7.org/fhir/StructureDefinition/shareablecodesystem"));
267    return cs;
268  }
269
270  public static void setOID(CodeSystem cs, String oid) {
271    if (!oid.startsWith("urn:oid:"))
272       oid = "urn:oid:" + oid;
273    if (!cs.hasIdentifier())
274      cs.addIdentifier(new Identifier().setSystem("urn:ietf:rfc:3986").setValue(oid));
275    else if ("urn:ietf:rfc:3986".equals(cs.getIdentifierFirstRep().getSystem()) && cs.getIdentifierFirstRep().hasValue() && cs.getIdentifierFirstRep().getValue().startsWith("urn:oid:"))
276      cs.getIdentifierFirstRep().setValue(oid);
277    else
278      throw new Error("unable to set OID on code system");
279    
280  }
281
282  public static boolean hasOID(CodeSystem cs) {
283    return getOID(cs) != null;
284  }
285
286  public static String getOID(CodeSystem cs) {
287    if (cs.hasIdentifier() && "urn:ietf:rfc:3986".equals(cs.getIdentifierFirstRep().getSystem()) && cs.getIdentifierFirstRep().hasValue() && cs.getIdentifierFirstRep().getValue().startsWith("urn:oid:"))
288        return cs.getIdentifierFirstRep().getValue().substring(8);
289    return null;
290  }
291
292  private static ConceptDefinitionComponent findCode(List<ConceptDefinitionComponent> list, String code) {
293    for (ConceptDefinitionComponent c : list) {
294      if (c.getCode().equals(code))
295        return c;
296      ConceptDefinitionComponent s = findCode(c.getConcept(), code);
297      if (s != null)
298        return s;
299    }
300    return null;
301  }
302
303  public static void markStatus(CodeSystem cs, String wg, StandardsStatus status, String pckage, String fmm, String normativeVersion) throws FHIRException {
304    if (wg != null) {
305      if (!ToolingExtensions.hasExtension(cs, ToolingExtensions.EXT_WORKGROUP) || 
306          (Utilities.existsInList(ToolingExtensions.readStringExtension(cs, ToolingExtensions.EXT_WORKGROUP), "fhir", "vocab") && !Utilities.existsInList(wg, "fhir", "vocab"))) {
307        ToolingExtensions.setCodeExtension(cs, ToolingExtensions.EXT_WORKGROUP, wg);
308      }
309    }
310    if (status != null) {
311      StandardsStatus ss = ToolingExtensions.getStandardsStatus(cs);
312      if (ss == null || ss.isLowerThan(status)) 
313        ToolingExtensions.setStandardsStatus(cs, status, normativeVersion);
314      if (pckage != null) {
315        if (!cs.hasUserData("ballot.package"))
316          cs.setUserData("ballot.package", pckage);
317        else if (!pckage.equals(cs.getUserString("ballot.package")))
318          if (!"infrastructure".equals(cs.getUserString("ballot.package")))
319            System.out.println("Code System "+cs.getUrl()+": ownership clash "+pckage+" vs "+cs.getUserString("ballot.package"));
320      }
321      if (status == StandardsStatus.NORMATIVE) {
322        cs.setExperimental(false);
323        cs.setStatus(PublicationStatus.ACTIVE);
324      }
325    }
326    if (fmm != null) {
327      String sfmm = ToolingExtensions.readStringExtension(cs, ToolingExtensions.EXT_FMM_LEVEL);
328      if (Utilities.noString(sfmm) || Integer.parseInt(sfmm) < Integer.parseInt(fmm)) 
329        ToolingExtensions.setIntegerExtension(cs, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(fmm));
330    }
331  }
332
333 
334  public static DataType readProperty(ConceptDefinitionComponent concept, String code) {
335    for (ConceptPropertyComponent p : concept.getProperty())
336      if (p.getCode().equals(code))
337        return p.getValue(); 
338    return null;
339  }
340
341  public static ConceptPropertyComponent getProperty(ConceptDefinitionComponent concept, String code) {
342    for (ConceptPropertyComponent p : concept.getProperty())
343      if (p.getCode().equals(code))
344        return p; 
345    return null;
346  }
347
348  // see http://hl7.org/fhir/R4/codesystem.html#hierachy
349  // returns additional parents not in the heirarchy
350  public static List<String> getOtherChildren(CodeSystem cs, ConceptDefinitionComponent c) {
351    List<String> res = new ArrayList<String>();
352    for (ConceptPropertyComponent p : c.getProperty()) {
353      if ("parent".equals(p.getCode())) {
354        res.add(p.getValue().primitiveValue());
355      }
356    }
357    return res;
358  }
359
360  // see http://hl7.org/fhir/R4/codesystem.html#hierachy
361  public static void addOtherChild(CodeSystem cs, ConceptDefinitionComponent owner, String code) {
362    defineChildProperty(cs);
363    owner.addProperty().setCode("child").setValue(new CodeType(code));
364  }
365
366  public static boolean hasProperty(ConceptDefinitionComponent c, String code) {
367    for (ConceptPropertyComponent cp : c.getProperty()) {
368      if (code.equals(cp.getCode())) {
369        return true;
370      }
371    }
372    return false;
373  }
374
375}