001package org.hl7.fhir.r5.utils;
002
003import org.hl7.fhir.r5.context.IWorkerContext;
004import org.hl7.fhir.r5.model.CanonicalResource;
005import org.hl7.fhir.r5.model.ElementDefinition;
006import org.hl7.fhir.r5.model.StructureDefinition;
007import org.hl7.fhir.r5.model.Enumerations.BindingStrength;
008
009public class R5Hacker {
010
011  public static void fixR5BrokenResources(IWorkerContext context) {
012    for (StructureDefinition sd : context.fetchResourcesByType(StructureDefinition.class)) {
013      fixSD(sd);
014    }
015  }
016
017
018  private static void fixSD(StructureDefinition sd) {
019    if ("5.0.0-ballot".equals(sd.getVersion()) && "ElementDefinition".equals(sd.getType())) {
020      for (ElementDefinition ed : sd.getDifferential().getElement()) {
021        hackEDR5BallotError(ed);
022      }
023      for (ElementDefinition ed : sd.getSnapshot().getElement()) {
024        hackEDR5BallotError(ed);
025      }
026    }
027    if ("5.0.0-ballot".equals(sd.getVersion()) && "Base".equals(sd.getType())) {
028      for (ElementDefinition ed : sd.getDifferential().getElement()) {
029        hackBaseR5BallotError(ed);
030      }
031      for (ElementDefinition ed : sd.getSnapshot().getElement()) {
032        hackBaseR5BallotError(ed);
033      }
034    }
035    if ("5.0.0-ballot".equals(sd.getVersion()) && "Bundle".equals(sd.getType())) {
036      for (ElementDefinition ed : sd.getDifferential().getElement()) {
037        hackBundleR5BallotError(ed);
038      }
039      for (ElementDefinition ed : sd.getSnapshot().getElement()) {
040        hackBundleR5BallotError(ed);
041      }
042    }
043    if ("5.0.0-ballot".equals(sd.getVersion()) && "http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype".equals(sd.getUrl())) {
044      sd.getContextFirstRep().setExpression("ElementDefinition");
045    }
046  }
047
048
049  private static void hackBaseR5BallotError(ElementDefinition ed) {
050    ed.getConstraint().clear(); 
051  }
052
053  private static void hackBundleR5BallotError(ElementDefinition ed) {
054    if (ed.getPath().equals("Bundle.link.relation")) {
055      ToolingExtensions.removeExtension(ed.getBinding(), ToolingExtensions.EXT_BINDING_NAME);
056    }    
057  }
058
059  private static void hackEDR5BallotError(ElementDefinition ed) {
060    if (ed.getPath().equals("ElementDefinition.type.code")) {
061      ed.getBinding().setStrength(BindingStrength.EXTENSIBLE);
062    }    
063  }
064
065
066  public static CanonicalResource fixR5BrokenResource(CanonicalResource cr) {
067    if (cr instanceof StructureDefinition) {
068      StructureDefinition sd = (StructureDefinition) cr;
069      fixSD(sd);
070    }
071    return cr;
072  }
073  
074}