001package org.hl7.fhir.r5.utils;
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.io.IOException;
025import java.io.UnsupportedEncodingException;
026import java.text.ParseException;
027import java.text.SimpleDateFormat;
028
029/*
030Copyright (c) 2011+, HL7, Inc
031  All rights reserved.
032
033  Redistribution and use in source and binary forms, with or without modification,
034  are permitted provided that the following conditions are met:
035
036   * Redistributions of source code must retain the above copyright notice, this
037     list of conditions and the following disclaimer.
038   * Redistributions in binary form must reproduce the above copyright notice,
039     this list of conditions and the following disclaimer in the documentation
040     and/or other materials provided with the distribution.
041   * Neither the name of HL7 nor the names of its contributors may be used to
042     endorse or promote products derived from this software without specific
043     prior written permission.
044
045  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
046  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
047  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
048  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
049  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
050  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
051  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
052  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
053  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
054  POSSIBILITY OF SUCH DAMAGE.
055
056*/
057
058import java.util.ArrayList;
059import java.util.Collections;
060import java.util.Date;
061import java.util.HashMap;
062import java.util.HashSet;
063import java.util.List;
064import java.util.Map;
065import java.util.Set;
066import java.util.concurrent.LinkedTransferQueue;
067
068import org.apache.commons.codec.binary.Base64;
069import org.apache.commons.io.output.ByteArrayOutputStream;
070import org.apache.commons.lang3.NotImplementedException;
071import org.hl7.fhir.exceptions.DefinitionException;
072import org.hl7.fhir.exceptions.FHIRException;
073import org.hl7.fhir.exceptions.FHIRFormatError;
074import org.hl7.fhir.exceptions.TerminologyServiceException;
075import org.hl7.fhir.r5.conformance.ProfileUtilities;
076import org.hl7.fhir.r5.conformance.ProfileUtilities.ProfileKnowledgeProvider;
077import org.hl7.fhir.r5.context.IWorkerContext;
078import org.hl7.fhir.r5.context.IWorkerContext.ValidationResult;
079import org.hl7.fhir.r5.formats.FormatUtilities;
080import org.hl7.fhir.r5.formats.IParser.OutputStyle;
081import org.hl7.fhir.r5.formats.XmlParser;
082import org.hl7.fhir.r5.model.Address;
083import org.hl7.fhir.r5.model.Annotation;
084import org.hl7.fhir.r5.model.Attachment;
085import org.hl7.fhir.r5.model.Base;
086import org.hl7.fhir.r5.model.Base64BinaryType;
087import org.hl7.fhir.r5.model.BooleanType;
088import org.hl7.fhir.r5.model.Bundle;
089import org.hl7.fhir.r5.model.Bundle.BundleEntryComponent;
090import org.hl7.fhir.r5.model.Bundle.BundleEntryRequestComponent;
091import org.hl7.fhir.r5.model.Bundle.BundleEntryResponseComponent;
092import org.hl7.fhir.r5.model.Bundle.BundleEntrySearchComponent;
093import org.hl7.fhir.r5.model.Bundle.BundleType;
094import org.hl7.fhir.r5.model.CapabilityStatement;
095import org.hl7.fhir.r5.model.CapabilityStatement.CapabilityStatementRestComponent;
096import org.hl7.fhir.r5.model.CapabilityStatement.CapabilityStatementRestResourceComponent;
097import org.hl7.fhir.r5.model.CapabilityStatement.ResourceInteractionComponent;
098import org.hl7.fhir.r5.model.CapabilityStatement.SystemInteractionComponent;
099import org.hl7.fhir.r5.model.CapabilityStatement.SystemRestfulInteraction;
100import org.hl7.fhir.r5.model.CapabilityStatement.TypeRestfulInteraction;
101import org.hl7.fhir.r5.model.CodeSystem;
102import org.hl7.fhir.r5.model.CodeSystem.CodeSystemContentMode;
103import org.hl7.fhir.r5.model.CodeSystem.CodeSystemFilterComponent;
104import org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionComponent;
105import org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionDesignationComponent;
106import org.hl7.fhir.r5.model.CodeSystem.ConceptPropertyComponent;
107import org.hl7.fhir.r5.model.CodeSystem.PropertyComponent;
108import org.hl7.fhir.r5.model.CodeType;
109import org.hl7.fhir.r5.model.CodeableConcept;
110import org.hl7.fhir.r5.model.Coding;
111import org.hl7.fhir.r5.model.CompartmentDefinition;
112import org.hl7.fhir.r5.model.CompartmentDefinition.CompartmentDefinitionResourceComponent;
113import org.hl7.fhir.r5.model.Composition;
114import org.hl7.fhir.r5.model.Composition.SectionComponent;
115import org.hl7.fhir.r5.model.ConceptMap;
116import org.hl7.fhir.r5.model.ConceptMap.ConceptMapGroupComponent;
117import org.hl7.fhir.r5.model.ConceptMap.OtherElementComponent;
118import org.hl7.fhir.r5.model.ConceptMap.SourceElementComponent;
119import org.hl7.fhir.r5.model.ConceptMap.TargetElementComponent;
120import org.hl7.fhir.r5.model.ContactDetail;
121import org.hl7.fhir.r5.model.ContactPoint;
122import org.hl7.fhir.r5.model.ContactPoint.ContactPointSystem;
123import org.hl7.fhir.r5.model.DateTimeType;
124import org.hl7.fhir.r5.model.DiagnosticReport;
125import org.hl7.fhir.r5.model.DomainResource;
126import org.hl7.fhir.r5.model.Dosage;
127import org.hl7.fhir.r5.model.ElementDefinition;
128import org.hl7.fhir.r5.model.Enumeration;
129import org.hl7.fhir.r5.model.Enumerations.ConceptMapRelationship;
130import org.hl7.fhir.r5.model.Extension;
131import org.hl7.fhir.r5.model.ExtensionHelper;
132import org.hl7.fhir.r5.model.HumanName;
133import org.hl7.fhir.r5.model.HumanName.NameUse;
134import org.hl7.fhir.r5.model.IdType;
135import org.hl7.fhir.r5.model.Identifier;
136import org.hl7.fhir.r5.model.ImplementationGuide;
137import org.hl7.fhir.r5.model.InstantType;
138import org.hl7.fhir.r5.model.Meta;
139import org.hl7.fhir.r5.model.MetadataResource;
140import org.hl7.fhir.r5.model.Narrative;
141import org.hl7.fhir.r5.model.Narrative.NarrativeStatus;
142import org.hl7.fhir.r5.model.OperationDefinition;
143import org.hl7.fhir.r5.model.OperationDefinition.OperationDefinitionParameterComponent;
144import org.hl7.fhir.r5.model.OperationOutcome;
145import org.hl7.fhir.r5.model.OperationOutcome.IssueSeverity;
146import org.hl7.fhir.r5.model.OperationOutcome.OperationOutcomeIssueComponent;
147import org.hl7.fhir.r5.model.Period;
148import org.hl7.fhir.r5.model.PrimitiveType;
149import org.hl7.fhir.r5.model.Property;
150import org.hl7.fhir.r5.model.Quantity;
151import org.hl7.fhir.r5.model.Questionnaire;
152import org.hl7.fhir.r5.model.Range;
153import org.hl7.fhir.r5.model.Ratio;
154import org.hl7.fhir.r5.model.Reference;
155import org.hl7.fhir.r5.model.RelatedArtifact;
156import org.hl7.fhir.r5.model.Resource;
157import org.hl7.fhir.r5.model.SampledData;
158import org.hl7.fhir.r5.model.Signature;
159import org.hl7.fhir.r5.model.StringType;
160import org.hl7.fhir.r5.model.StructureDefinition;
161import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind;
162import org.hl7.fhir.r5.model.Timing;
163import org.hl7.fhir.r5.model.Timing.EventTiming;
164import org.hl7.fhir.r5.model.Timing.TimingRepeatComponent;
165import org.hl7.fhir.r5.model.Timing.UnitsOfTime;
166import org.hl7.fhir.r5.model.Type;
167import org.hl7.fhir.r5.model.UriType;
168import org.hl7.fhir.r5.model.UsageContext;
169import org.hl7.fhir.r5.model.ValueSet;
170import org.hl7.fhir.r5.model.ValueSet.ConceptReferenceComponent;
171import org.hl7.fhir.r5.model.ValueSet.ConceptReferenceDesignationComponent;
172import org.hl7.fhir.r5.model.ValueSet.ConceptSetComponent;
173import org.hl7.fhir.r5.model.ValueSet.ConceptSetFilterComponent;
174import org.hl7.fhir.r5.model.ValueSet.FilterOperator;
175import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionComponent;
176import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionContainsComponent;
177import org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionParameterComponent;
178import org.hl7.fhir.r5.terminologies.CodeSystemUtilities;
179import org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
180import org.hl7.fhir.r5.utils.FHIRPathEngine.IEvaluationContext;
181import org.hl7.fhir.r5.utils.LiquidEngine.LiquidDocument;
182import org.hl7.fhir.r5.utils.NarrativeGenerator.ILiquidTemplateProvider;
183import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
184import org.hl7.fhir.utilities.MarkDownProcessor;
185import org.hl7.fhir.utilities.TerminologyServiceOptions;
186import org.hl7.fhir.utilities.MarkDownProcessor.Dialect;
187import org.hl7.fhir.utilities.Utilities;
188import org.hl7.fhir.utilities.xhtml.NodeType;
189import org.hl7.fhir.utilities.xhtml.XhtmlComposer;
190import org.hl7.fhir.utilities.xhtml.XhtmlNode;
191import org.hl7.fhir.utilities.xhtml.XhtmlParser;
192import org.hl7.fhir.utilities.xml.XMLUtil;
193import org.hl7.fhir.utilities.xml.XmlGenerator;
194import org.w3c.dom.Element;
195
196public class NarrativeGenerator implements INarrativeGenerator {
197
198  public interface ILiquidTemplateProvider {
199
200    String findTemplate(ResourceContext rcontext, DomainResource r);
201
202  }
203
204  public interface ITypeParser {
205    Base parseType(String xml, String type) throws FHIRFormatError, IOException, FHIRException ;
206  }
207
208  public class ConceptMapRenderInstructions {
209    private String name;
210    private String url;
211    private boolean doDescription;
212    public ConceptMapRenderInstructions(String name, String url, boolean doDescription) {
213      super();
214      this.name = name;
215      this.url = url;
216      this.doDescription = doDescription;
217    }
218    public String getName() {
219      return name;
220    }
221    public String getUrl() {
222      return url;
223    }
224    public boolean isDoDescription() {
225      return doDescription;
226    }
227    
228  }
229
230  public class UsedConceptMap {
231
232    private ConceptMapRenderInstructions details;
233    private String link;
234    private ConceptMap map;
235    public UsedConceptMap(ConceptMapRenderInstructions details, String link, ConceptMap map) {
236      super();
237      this.details = details;
238      this.link = link;
239      this.map = map;
240    }
241    public ConceptMapRenderInstructions getDetails() {
242      return details;
243    }
244    public ConceptMap getMap() {
245      return map;
246    }
247    public String getLink() {
248      return link;
249    }    
250  }
251
252  public static class ResourceContext {
253    Bundle bundleResource;
254    
255    DomainResource resourceResource;
256    
257    public ResourceContext(Bundle bundle, DomainResource dr) {
258      super();
259      this.bundleResource = bundle;
260      this.resourceResource = dr;
261    }
262
263    public ResourceContext(Element bundle, Element doc) {
264    }
265
266    public ResourceContext(org.hl7.fhir.r5.elementmodel.Element bundle, org.hl7.fhir.r5.elementmodel.Element er) {
267    }
268
269    public Resource resolve(String value) {
270      if (value.startsWith("#")) {
271        for (Resource r : resourceResource.getContained()) {
272          if (r.getId().equals(value.substring(1)))
273            return r;
274        }
275        return null;
276      }
277      if (bundleResource != null) {
278        for (BundleEntryComponent be : bundleResource.getEntry()) {
279          if (be.getFullUrl().equals(value))
280            return be.getResource();
281          if (value.equals(be.getResource().fhirType()+"/"+be.getResource().getId()))
282            return be.getResource();
283        }
284      }
285      return null;
286    }
287  }
288
289  private static final String ABSTRACT_CODE_HINT = "This code is not selectable ('Abstract')";
290
291  public interface IReferenceResolver {
292    ResourceWithReference resolve(String url);
293  }
294
295  private Bundle bundle;
296  private String definitionsTarget;
297  private String corePath;
298  private String destDir;
299  private String snomedEdition;
300  private ProfileKnowledgeProvider pkp;
301  private MarkDownProcessor markdown = new MarkDownProcessor(Dialect.COMMON_MARK);
302  private ITypeParser parser; // when generating for an element model
303  private ILiquidTemplateProvider templateProvider;
304  private IEvaluationContext services;
305  
306  public boolean generate(Bundle b, boolean evenIfAlreadyHasNarrative, Set<String> outputTracker) throws EOperationOutcome, FHIRException, IOException {
307    boolean res = false;
308    this.bundle = b;
309    for (BundleEntryComponent be : b.getEntry()) {
310      if (be.hasResource() && be.getResource() instanceof DomainResource) {
311        DomainResource dr = (DomainResource) be.getResource();
312        if (evenIfAlreadyHasNarrative || !dr.getText().hasDiv())
313          res = generate(new ResourceContext(b, dr), dr, outputTracker) || res;
314      }
315    }
316    return res;
317  }
318
319  public boolean generate(DomainResource r, Set<String> outputTracker) throws EOperationOutcome, FHIRException, IOException {
320    return generate(null, r, outputTracker);
321  }
322  
323  public boolean generate(ResourceContext rcontext, DomainResource r, Set<String> outputTracker) throws EOperationOutcome, FHIRException, IOException {
324    if (rcontext == null)
325      rcontext = new ResourceContext(null, r);
326    
327    if (templateProvider != null) {
328      String liquidTemplate = templateProvider.findTemplate(rcontext, r);
329      if (liquidTemplate != null) {
330         return generateByLiquid(rcontext, r, liquidTemplate, outputTracker);
331      }
332    }
333    if (r instanceof ConceptMap) {
334      return generate(rcontext, (ConceptMap) r); // Maintainer = Grahame
335    } else if (r instanceof ValueSet) {
336      return generate(rcontext, (ValueSet) r, true); // Maintainer = Grahame
337    } else if (r instanceof CodeSystem) {
338      return generate(rcontext, (CodeSystem) r, true, null); // Maintainer = Grahame
339    } else if (r instanceof OperationOutcome) {
340      return generate(rcontext, (OperationOutcome) r); // Maintainer = Grahame
341    } else if (r instanceof CapabilityStatement) {
342      return generate(rcontext, (CapabilityStatement) r);   // Maintainer = Grahame
343    } else if (r instanceof CompartmentDefinition) {
344      return generate(rcontext, (CompartmentDefinition) r);   // Maintainer = Grahame
345    } else if (r instanceof OperationDefinition) {
346      return generate(rcontext, (OperationDefinition) r);   // Maintainer = Grahame
347    } else if (r instanceof StructureDefinition) {
348      return generate(rcontext, (StructureDefinition) r, outputTracker);   // Maintainer = Grahame
349    } else if (r instanceof ImplementationGuide) {
350      return generate(rcontext, (ImplementationGuide) r);   // Maintainer = Lloyd (until Grahame wants to take over . . . :))
351    } else if (r instanceof DiagnosticReport) {
352      inject(r, generateDiagnosticReport(new ResourceWrapperDirect(r)),  NarrativeStatus.GENERATED);   // Maintainer = Grahame
353      return true;
354    } else {
355      StructureDefinition p = null;
356      if (r.hasMeta())
357        for (UriType pu : r.getMeta().getProfile())
358          if (p == null)
359            p = context.fetchResource(StructureDefinition.class, pu.getValue());
360      if (p == null)
361        p = context.fetchResource(StructureDefinition.class, r.getResourceType().toString());
362      if (p == null)
363        p = context.fetchTypeDefinition(r.getResourceType().toString().toLowerCase());
364      if (p != null)
365        return generateByProfile(rcontext, p, true);
366      else
367        return false;
368    }
369  }
370
371  private boolean generateByLiquid(ResourceContext rcontext, DomainResource r, String liquidTemplate, Set<String> outputTracker) {
372
373    LiquidEngine engine = new LiquidEngine(context, services);
374    XhtmlNode x;
375    try {
376      LiquidDocument doc = engine.parse(liquidTemplate, "template");
377      String html = engine.evaluate(doc, r, rcontext);
378      x = new XhtmlParser().parseFragment(html);
379      if (!x.getName().equals("div"))
380        throw new FHIRException("Error in template: Root element is not 'div'");
381    } catch (FHIRException | IOException e) {
382      x = new XhtmlNode(NodeType.Element, "div");
383      x.para().b().setAttribute("style", "color: maroon").tx("Exception generating Narrative: "+e.getMessage());
384    }
385    inject(r, x,  NarrativeStatus.GENERATED);
386    return true;
387  }
388
389  private interface PropertyWrapper {
390    public String getName();
391    public boolean hasValues();
392    public List<BaseWrapper> getValues();
393    public String getTypeCode();
394    public String getDefinition();
395    public int getMinCardinality();
396    public int getMaxCardinality();
397    public StructureDefinition getStructure();
398    public BaseWrapper value();
399  }
400
401  private interface ResourceWrapper {
402    public List<ResourceWrapper> getContained();
403    public String getId();
404    public XhtmlNode getNarrative() throws FHIRFormatError, IOException, FHIRException;
405    public String getName();
406    public List<PropertyWrapper> children();
407  }
408
409  private interface BaseWrapper {
410    public Base getBase() throws UnsupportedEncodingException, IOException, FHIRException;
411    public List<PropertyWrapper> children();
412    public PropertyWrapper getChildByName(String tail);
413  }
414
415  private class BaseWrapperElement implements BaseWrapper {
416    private Element element;
417    private String type;
418    private StructureDefinition structure;
419    private ElementDefinition definition;
420    private List<ElementDefinition> children;
421    private List<PropertyWrapper> list;
422
423    public BaseWrapperElement(Element element, String type, StructureDefinition structure, ElementDefinition definition) {
424      this.element = element;
425      this.type = type;
426      this.structure = structure;
427      this.definition = definition;
428    }
429
430    @Override
431    public Base getBase() throws UnsupportedEncodingException, IOException, FHIRException {
432      if (type == null || type.equals("Resource") || type.equals("BackboneElement") || type.equals("Element"))
433        return null;
434
435    String xml;
436                try {
437                        xml = new XmlGenerator().generate(element);
438                } catch (org.hl7.fhir.exceptions.FHIRException e) {
439                        throw new FHIRException(e.getMessage(), e);
440                }
441      return parseType(xml, type);
442    }
443
444    @Override
445    public List<PropertyWrapper> children() {
446      if (list == null) {
447        children = ProfileUtilities.getChildList(structure, definition);
448        list = new ArrayList<NarrativeGenerator.PropertyWrapper>();
449        for (ElementDefinition child : children) {
450          List<Element> elements = new ArrayList<Element>();
451          XMLUtil.getNamedChildrenWithWildcard(element, tail(child.getPath()), elements);
452          list.add(new PropertyWrapperElement(structure, child, elements));
453        }
454      }
455      return list;
456    }
457
458    @Override
459    public PropertyWrapper getChildByName(String name) {
460      for (PropertyWrapper p : children())
461        if (p.getName().equals(name))
462          return p;
463      return null;
464    }
465
466  }
467
468  private class PropertyWrapperElement implements PropertyWrapper {
469
470    private StructureDefinition structure;
471    private ElementDefinition definition;
472    private List<Element> values;
473    private List<BaseWrapper> list;
474
475    public PropertyWrapperElement(StructureDefinition structure, ElementDefinition definition, List<Element> values) {
476      this.structure = structure;
477      this.definition = definition;
478      this.values = values;
479    }
480
481    @Override
482    public String getName() {
483      return tail(definition.getPath());
484    }
485
486    @Override
487    public boolean hasValues() {
488      return values.size() > 0;
489    }
490
491    @Override
492    public List<BaseWrapper> getValues() {
493      if (list == null) {
494        list = new ArrayList<NarrativeGenerator.BaseWrapper>();
495        for (Element e : values)
496          list.add(new BaseWrapperElement(e, determineType(e), structure, definition));
497      }
498      return list;
499    }
500    private String determineType(Element e) {
501      if (definition.getType().isEmpty())
502        return null;
503      if (definition.getType().size() == 1) {
504        if (definition.getType().get(0).getWorkingCode().equals("Element") || definition.getType().get(0).getWorkingCode().equals("BackboneElement"))
505          return null;
506        return definition.getType().get(0).getWorkingCode();
507      }
508      String t = e.getNodeName().substring(tail(definition.getPath()).length()-3);
509
510      if (isPrimitive(Utilities.uncapitalize(t)))
511        return Utilities.uncapitalize(t);
512      else
513        return t;
514    }
515
516    private boolean isPrimitive(String code) {
517      StructureDefinition sd = context.fetchTypeDefinition(code);
518      return sd != null && sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE;
519    }
520
521    @Override
522    public String getTypeCode() {
523      if (definition == null || definition.getType().size() != 1)
524        throw new Error("not handled");
525      return definition.getType().get(0).getWorkingCode();
526    }
527
528    @Override
529    public String getDefinition() {
530      if (definition == null)
531        throw new Error("not handled");
532      return definition.getDefinition();
533    }
534
535    @Override
536    public int getMinCardinality() {
537      if (definition == null)
538        throw new Error("not handled");
539      return definition.getMin();
540    }
541
542    @Override
543    public int getMaxCardinality() {
544      if (definition == null)
545        throw new Error("not handled");
546      return definition.getMax().equals("*") ? Integer.MAX_VALUE : Integer.parseInt(definition.getMax());
547    }
548
549    @Override
550    public StructureDefinition getStructure() {
551      return structure;
552    }
553
554    @Override
555    public BaseWrapper value() {
556      if (getValues().size() != 1)
557        throw new Error("Access single value, but value count is "+getValues().size());
558      return getValues().get(0);
559    }
560
561  }
562
563  private class BaseWrapperMetaElement implements BaseWrapper {
564    private org.hl7.fhir.r5.elementmodel.Element element;
565    private String type;
566    private StructureDefinition structure;
567    private ElementDefinition definition;
568    private List<ElementDefinition> children;
569    private List<PropertyWrapper> list;
570
571    public BaseWrapperMetaElement(org.hl7.fhir.r5.elementmodel.Element element, String type, StructureDefinition structure, ElementDefinition definition) {
572      this.element = element;
573      this.type = type;
574      this.structure = structure;
575      this.definition = definition;
576    }
577
578    @Override
579    public Base getBase() throws UnsupportedEncodingException, IOException, FHIRException {
580      if (type == null || type.equals("Resource") || type.equals("BackboneElement") || type.equals("Element"))
581        return null;
582
583      if (element.hasElementProperty())
584        return null;
585      ByteArrayOutputStream xml = new ByteArrayOutputStream();
586      try {
587        new org.hl7.fhir.r5.elementmodel.XmlParser(context).compose(element, xml, OutputStyle.PRETTY, null);
588      } catch (Exception e) {
589        throw new FHIRException(e.getMessage(), e);
590      }
591      return parseType(xml.toString(), type); 
592    }
593
594    @Override
595    public List<PropertyWrapper> children() {
596      if (list == null) {
597        children = ProfileUtilities.getChildList(structure, definition);
598        list = new ArrayList<NarrativeGenerator.PropertyWrapper>();
599        for (ElementDefinition child : children) {
600          List<org.hl7.fhir.r5.elementmodel.Element> elements = new ArrayList<org.hl7.fhir.r5.elementmodel.Element>();
601          String name = tail(child.getPath());
602          if (name.endsWith("[x]"))
603            element.getNamedChildrenWithWildcard(name, elements);
604          else
605            element.getNamedChildren(name, elements);
606          list.add(new PropertyWrapperMetaElement(structure, child, elements));
607        }
608      }
609      return list;
610    }
611
612    @Override
613    public PropertyWrapper getChildByName(String name) {
614      for (PropertyWrapper p : children())
615        if (p.getName().equals(name))
616          return p;
617      return null;
618    }
619
620  }
621  public class ResourceWrapperMetaElement implements ResourceWrapper {
622    private org.hl7.fhir.r5.elementmodel.Element wrapped;
623    private List<ResourceWrapper> list;
624    private List<PropertyWrapper> list2;
625    private StructureDefinition definition;
626    public ResourceWrapperMetaElement(org.hl7.fhir.r5.elementmodel.Element wrapped) {
627      this.wrapped = wrapped;
628      this.definition = wrapped.getProperty().getStructure();
629    }
630
631    @Override
632    public List<ResourceWrapper> getContained() {
633      if (list == null) {
634        List<org.hl7.fhir.r5.elementmodel.Element> children = wrapped.getChildrenByName("contained");
635        list = new ArrayList<NarrativeGenerator.ResourceWrapper>();
636        for (org.hl7.fhir.r5.elementmodel.Element e : children) {
637          list.add(new ResourceWrapperMetaElement(e));
638        }
639      }
640      return list;
641    }
642
643    @Override
644    public String getId() {
645      return wrapped.getNamedChildValue("id");
646    }
647
648    @Override
649    public XhtmlNode getNarrative() throws FHIRFormatError, IOException, FHIRException {
650      org.hl7.fhir.r5.elementmodel.Element txt = wrapped.getNamedChild("text");
651      if (txt == null)
652        return null;
653      org.hl7.fhir.r5.elementmodel.Element div = txt.getNamedChild("div");
654      if (div == null)
655        return null;
656      else
657        return div.getXhtml();
658    }
659
660    @Override
661    public String getName() {
662      return wrapped.getName();
663    }
664
665    @Override
666    public List<PropertyWrapper> children() {
667      if (list2 == null) {
668        List<ElementDefinition> children = ProfileUtilities.getChildList(definition, definition.getSnapshot().getElement().get(0));
669        list2 = new ArrayList<NarrativeGenerator.PropertyWrapper>();
670        for (ElementDefinition child : children) {
671          List<org.hl7.fhir.r5.elementmodel.Element> elements = new ArrayList<org.hl7.fhir.r5.elementmodel.Element>();
672          if (child.getPath().endsWith("[x]"))
673            wrapped.getNamedChildrenWithWildcard(tail(child.getPath()), elements);
674          else
675            wrapped.getNamedChildren(tail(child.getPath()), elements);
676          list2.add(new PropertyWrapperMetaElement(definition, child, elements));
677        }
678      }
679      return list2;
680    }
681  }
682
683  private class PropertyWrapperMetaElement implements PropertyWrapper {
684
685    private StructureDefinition structure;
686    private ElementDefinition definition;
687    private List<org.hl7.fhir.r5.elementmodel.Element> values;
688    private List<BaseWrapper> list;
689
690    public PropertyWrapperMetaElement(StructureDefinition structure, ElementDefinition definition, List<org.hl7.fhir.r5.elementmodel.Element> values) {
691      this.structure = structure;
692      this.definition = definition;
693      this.values = values;
694    }
695
696    @Override
697    public String getName() {
698      return tail(definition.getPath());
699    }
700
701    @Override
702    public boolean hasValues() {
703      return values.size() > 0;
704    }
705
706    @Override
707    public List<BaseWrapper> getValues() {
708      if (list == null) {
709        list = new ArrayList<NarrativeGenerator.BaseWrapper>();
710        for (org.hl7.fhir.r5.elementmodel.Element e : values)
711          list.add(new BaseWrapperMetaElement(e, e.fhirType(), structure, definition));
712      }
713      return list;
714    }
715
716    @Override
717    public String getTypeCode() {
718      return definition.typeSummary();
719    }
720
721    @Override
722    public String getDefinition() {
723      return definition.getDefinition();
724    }
725
726    @Override
727    public int getMinCardinality() {
728      return definition.getMin();
729    }
730
731    @Override
732    public int getMaxCardinality() {
733      return "*".equals(definition.getMax()) ? Integer.MAX_VALUE : Integer.valueOf(definition.getMax());
734    }
735
736    @Override
737    public StructureDefinition getStructure() {
738      return structure;
739    }
740
741    @Override
742    public BaseWrapper value() {
743      if (getValues().size() != 1)
744        throw new Error("Access single value, but value count is "+getValues().size());
745      return getValues().get(0);
746    }
747
748  }
749
750  private class ResourceWrapperElement implements ResourceWrapper {
751
752    private Element wrapped;
753    private StructureDefinition definition;
754    private List<ResourceWrapper> list;
755    private List<PropertyWrapper> list2;
756
757    public ResourceWrapperElement(Element wrapped, StructureDefinition definition) {
758      this.wrapped = wrapped;
759      this.definition = definition;
760    }
761
762    @Override
763    public List<ResourceWrapper> getContained() {
764      if (list == null) {
765        List<Element> children = new ArrayList<Element>();
766        XMLUtil.getNamedChildren(wrapped, "contained", children);
767        list = new ArrayList<NarrativeGenerator.ResourceWrapper>();
768        for (Element e : children) {
769          Element c = XMLUtil.getFirstChild(e);
770          list.add(new ResourceWrapperElement(c, context.fetchTypeDefinition(c.getNodeName())));
771        }
772      }
773      return list;
774    }
775
776    @Override
777    public String getId() {
778      return XMLUtil.getNamedChildValue(wrapped, "id");
779    }
780
781    @Override
782    public XhtmlNode getNarrative() throws FHIRFormatError, IOException, FHIRException {
783      Element txt = XMLUtil.getNamedChild(wrapped, "text");
784      if (txt == null)
785        return null;
786      Element div = XMLUtil.getNamedChild(txt, "div");
787      if (div == null)
788        return null;
789      try {
790                        return new XhtmlParser().parse(new XmlGenerator().generate(div), "div");
791                } catch (org.hl7.fhir.exceptions.FHIRFormatError e) {
792                        throw new FHIRFormatError(e.getMessage(), e);
793                } catch (org.hl7.fhir.exceptions.FHIRException e) {
794                        throw new FHIRException(e.getMessage(), e);
795                }
796    }
797
798    @Override
799    public String getName() {
800      return wrapped.getNodeName();
801    }
802
803    @Override
804    public List<PropertyWrapper> children() {
805      if (list2 == null) {
806        List<ElementDefinition> children = ProfileUtilities.getChildList(definition, definition.getSnapshot().getElement().get(0));
807        list2 = new ArrayList<NarrativeGenerator.PropertyWrapper>();
808        for (ElementDefinition child : children) {
809          List<Element> elements = new ArrayList<Element>();
810          XMLUtil.getNamedChildrenWithWildcard(wrapped, tail(child.getPath()), elements);
811          list2.add(new PropertyWrapperElement(definition, child, elements));
812        }
813      }
814      return list2;
815    }
816  }
817
818  private class PropertyWrapperDirect implements PropertyWrapper {
819    private Property wrapped;
820    private List<BaseWrapper> list;
821
822    private PropertyWrapperDirect(Property wrapped) {
823      super();
824      if (wrapped == null)
825        throw new Error("wrapped == null");
826      this.wrapped = wrapped;
827    }
828
829    @Override
830    public String getName() {
831      return wrapped.getName();
832    }
833
834    @Override
835    public boolean hasValues() {
836      return wrapped.hasValues();
837    }
838
839    @Override
840    public List<BaseWrapper> getValues() {
841      if (list == null) {
842        list = new ArrayList<NarrativeGenerator.BaseWrapper>();
843        for (Base b : wrapped.getValues())
844          list.add(b == null ? null : new BaseWrapperDirect(b));
845      }
846      return list;
847    }
848
849    @Override
850    public String getTypeCode() {
851      return wrapped.getTypeCode();
852    }
853
854    @Override
855    public String getDefinition() {
856      return wrapped.getDefinition();
857    }
858
859    @Override
860    public int getMinCardinality() {
861      return wrapped.getMinCardinality();
862    }
863
864    @Override
865    public int getMaxCardinality() {
866      return wrapped.getMinCardinality();
867    }
868
869    @Override
870    public StructureDefinition getStructure() {
871      return wrapped.getStructure();
872    }
873
874    @Override
875    public BaseWrapper value() {
876      if (getValues().size() != 1)
877        throw new Error("Access single value, but value count is "+getValues().size());
878      return getValues().get(0);
879    }
880    
881    public String toString() {
882      return "#."+wrapped.toString();
883    }
884  }
885
886  private class BaseWrapperDirect implements BaseWrapper {
887    private Base wrapped;
888    private List<PropertyWrapper> list;
889
890    private BaseWrapperDirect(Base wrapped) {
891      super();
892      if (wrapped == null)
893        throw new Error("wrapped == null");
894      this.wrapped = wrapped;
895    }
896
897    @Override
898    public Base getBase() {
899      return wrapped;
900    }
901
902    @Override
903    public List<PropertyWrapper> children() {
904      if (list == null) {
905        list = new ArrayList<NarrativeGenerator.PropertyWrapper>();
906        for (Property p : wrapped.children())
907          list.add(new PropertyWrapperDirect(p));
908      }
909      return list;
910
911    }
912
913    @Override
914    public PropertyWrapper getChildByName(String name) {
915      Property p = wrapped.getChildByName(name);
916      if (p == null)
917        return null;
918      else
919        return new PropertyWrapperDirect(p);
920    }
921
922  }
923
924  public class ResourceWrapperDirect implements ResourceWrapper {
925    private Resource wrapped;
926
927    public ResourceWrapperDirect(Resource wrapped) {
928      super();
929      if (wrapped == null)
930        throw new Error("wrapped == null");
931      this.wrapped = wrapped;
932    }
933
934    @Override
935    public List<ResourceWrapper> getContained() {
936      List<ResourceWrapper> list = new ArrayList<NarrativeGenerator.ResourceWrapper>();
937      if (wrapped instanceof DomainResource) {
938        DomainResource dr = (DomainResource) wrapped;
939        for (Resource c : dr.getContained()) {
940          list.add(new ResourceWrapperDirect(c));
941        }
942      }
943      return list;
944    }
945
946    @Override
947    public String getId() {
948      return wrapped.getId();
949    }
950
951    @Override
952    public XhtmlNode getNarrative() {
953      if (wrapped instanceof DomainResource) {
954        DomainResource dr = (DomainResource) wrapped;
955        if (dr.hasText() && dr.getText().hasDiv())
956          return dr.getText().getDiv();
957      }
958      return null;
959    }
960
961    @Override
962    public String getName() {
963      return wrapped.getResourceType().toString();
964    }
965
966    @Override
967    public List<PropertyWrapper> children() {
968      List<PropertyWrapper> list = new ArrayList<PropertyWrapper>();
969      for (Property c : wrapped.children())
970        list.add(new PropertyWrapperDirect(c));
971      return list;
972    }
973  }
974
975  public static class ResourceWithReference {
976
977    private String reference;
978    private ResourceWrapper resource;
979
980    public ResourceWithReference(String reference, ResourceWrapper resource) {
981      this.reference = reference;
982      this.resource = resource;
983    }
984
985    public String getReference() {
986      return reference;
987    }
988
989    public ResourceWrapper getResource() {
990      return resource;
991    }
992  }
993
994  private String prefix;
995  private IWorkerContext context;
996  private String basePath;
997  private String tooCostlyNoteEmpty;
998  private String tooCostlyNoteNotEmpty;
999  private IReferenceResolver resolver;
1000  private int headerLevelContext;
1001  private List<ConceptMapRenderInstructions> renderingMaps = new ArrayList<ConceptMapRenderInstructions>();
1002  private boolean pretty;
1003  private boolean canonicalUrlsAsLinks;
1004  private TerminologyServiceOptions terminologyServiceOptions = new TerminologyServiceOptions();
1005  private boolean noSlowLookup;
1006  private List<String> codeSystemPropList = new ArrayList<>();
1007
1008  public NarrativeGenerator(String prefix, String basePath, IWorkerContext context) {
1009    super();
1010    this.prefix = prefix;
1011    this.context = context;
1012    this.basePath = basePath;
1013    init();
1014  }
1015  
1016  public NarrativeGenerator setLiquidServices(ILiquidTemplateProvider templateProvider, IEvaluationContext services) {
1017    this.templateProvider = templateProvider;
1018    this.services = services;
1019    return this;
1020  }
1021
1022  public Base parseType(String xml, String type) throws IOException, FHIRException {
1023    if (parser != null)
1024      return parser.parseType(xml, type);
1025    else
1026      return new XmlParser().parseAnyType(xml, type);
1027  }
1028
1029  public NarrativeGenerator(String prefix, String basePath, IWorkerContext context, IReferenceResolver resolver) {
1030    super();
1031    this.prefix = prefix;
1032    this.context = context;
1033    this.basePath = basePath;
1034    this.resolver = resolver;
1035    init();
1036  }
1037
1038
1039  private void init() {
1040    renderingMaps.add(new ConceptMapRenderInstructions("Canonical Status", "http://hl7.org/fhir/ValueSet/resource-status", false));
1041  }
1042
1043  public List<ConceptMapRenderInstructions> getRenderingMaps() {
1044    return renderingMaps;
1045  }
1046
1047  public int getHeaderLevelContext() {
1048    return headerLevelContext;
1049  }
1050
1051  public NarrativeGenerator setHeaderLevelContext(int headerLevelContext) {
1052    this.headerLevelContext = headerLevelContext;
1053    return this;
1054  }
1055
1056  public String getTooCostlyNoteEmpty() {
1057    return tooCostlyNoteEmpty;
1058  }
1059
1060
1061  public NarrativeGenerator setTooCostlyNoteEmpty(String tooCostlyNoteEmpty) {
1062    this.tooCostlyNoteEmpty = tooCostlyNoteEmpty;
1063    return this;
1064  }
1065
1066
1067  public String getTooCostlyNoteNotEmpty() {
1068    return tooCostlyNoteNotEmpty;
1069  }
1070
1071
1072  public NarrativeGenerator setTooCostlyNoteNotEmpty(String tooCostlyNoteNotEmpty) {
1073    this.tooCostlyNoteNotEmpty = tooCostlyNoteNotEmpty;
1074    return this;
1075  }
1076
1077
1078  // dom based version, for build program
1079  public String generate(Element doc) throws IOException, org.hl7.fhir.exceptions.FHIRException {
1080    return generate(null, doc);
1081  }
1082  public String generate(ResourceContext rcontext, Element doc) throws IOException, org.hl7.fhir.exceptions.FHIRException {
1083    if (rcontext == null)
1084      rcontext = new ResourceContext(null, doc);
1085    String rt = "http://hl7.org/fhir/StructureDefinition/"+doc.getNodeName();
1086    StructureDefinition p = context.fetchResource(StructureDefinition.class, rt);
1087    return generateByProfile(doc, p, true);
1088  }
1089
1090  // dom based version, for build program
1091  public String generate(org.hl7.fhir.r5.elementmodel.Element er, boolean showCodeDetails, ITypeParser parser) throws IOException, FHIRException {
1092    return generate(null, er, showCodeDetails, parser);
1093  }
1094  
1095  public String generate(ResourceContext rcontext, org.hl7.fhir.r5.elementmodel.Element er, boolean showCodeDetails, ITypeParser parser) throws IOException, FHIRException {
1096    if (rcontext == null)
1097      rcontext = new ResourceContext(null, er);
1098    this.parser = parser;
1099    
1100    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
1101    x.para().b().tx("Generated Narrative"+(showCodeDetails ? " with Details" : ""));
1102    try {
1103      ResourceWrapperMetaElement resw = new ResourceWrapperMetaElement(er);
1104      BaseWrapperMetaElement base = new BaseWrapperMetaElement(er, null, er.getProperty().getStructure(), er.getProperty().getDefinition());
1105      base.children();
1106      generateByProfile(resw, er.getProperty().getStructure(), base, er.getProperty().getStructure().getSnapshot().getElement(), er.getProperty().getDefinition(), base.children, x, er.fhirType(), showCodeDetails, 0, rcontext);
1107
1108    } catch (Exception e) {
1109      e.printStackTrace();
1110      x.para().b().setAttribute("style", "color: maroon").tx("Exception generating Narrative: "+e.getMessage());
1111    }
1112    inject(er, x,  NarrativeStatus.GENERATED);
1113    return new XhtmlComposer(XhtmlComposer.XML, pretty).compose(x);
1114  }
1115
1116  private boolean generateByProfile(ResourceContext rc, StructureDefinition profile, boolean showCodeDetails) {
1117    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
1118    x.para().b().tx("Generated Narrative"+(showCodeDetails ? " with Details" : ""));
1119    try {
1120      generateByProfile(rc.resourceResource, profile, rc.resourceResource, profile.getSnapshot().getElement(), profile.getSnapshot().getElement().get(0), getChildrenForPath(profile.getSnapshot().getElement(), rc.resourceResource.getResourceType().toString()), x, rc.resourceResource.getResourceType().toString(), showCodeDetails, rc);
1121    } catch (Exception e) {
1122      e.printStackTrace();
1123      x.para().b().setAttribute("style", "color: maroon").tx("Exception generating Narrative: "+e.getMessage());
1124    }
1125    inject(rc.resourceResource, x,  NarrativeStatus.GENERATED);
1126    return true;
1127  }
1128
1129  private String generateByProfile(Element er, StructureDefinition profile, boolean showCodeDetails) throws IOException, org.hl7.fhir.exceptions.FHIRException {
1130    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
1131    x.para().b().tx("Generated Narrative"+(showCodeDetails ? " with Details" : ""));
1132    try {
1133      generateByProfile(er, profile, er, profile.getSnapshot().getElement(), profile.getSnapshot().getElement().get(0), getChildrenForPath(profile.getSnapshot().getElement(), er.getLocalName()), x, er.getLocalName(), showCodeDetails);
1134    } catch (Exception e) {
1135      e.printStackTrace();
1136      x.para().b().setAttribute("style", "color: maroon").tx("Exception generating Narrative: "+e.getMessage());
1137    }
1138    inject(er, x,  NarrativeStatus.GENERATED);
1139    String b = new XhtmlComposer(XhtmlComposer.XML, pretty).compose(x);
1140    return b;
1141  }
1142
1143  private void generateByProfile(Element eres, StructureDefinition profile, Element ee, List<ElementDefinition> allElements, ElementDefinition defn, List<ElementDefinition> children,  XhtmlNode x, String path, boolean showCodeDetails) throws FHIRException, UnsupportedEncodingException, IOException {
1144
1145    ResourceWrapperElement resw = new ResourceWrapperElement(eres, profile);
1146    BaseWrapperElement base = new BaseWrapperElement(ee, null, profile, profile.getSnapshot().getElement().get(0));
1147    generateByProfile(resw, profile, base, allElements, defn, children, x, path, showCodeDetails, 0, null);
1148  }
1149
1150
1151  private void generateByProfile(Resource res, StructureDefinition profile, Base e, List<ElementDefinition> allElements, ElementDefinition defn, List<ElementDefinition> children,  XhtmlNode x, String path, boolean showCodeDetails, ResourceContext rc) throws FHIRException, UnsupportedEncodingException, IOException {
1152    generateByProfile(new ResourceWrapperDirect(res), profile, new BaseWrapperDirect(e), allElements, defn, children, x, path, showCodeDetails, 0, rc);
1153  }
1154
1155  private void generateByProfile(ResourceWrapper res, StructureDefinition profile, BaseWrapper e, List<ElementDefinition> allElements, ElementDefinition defn, List<ElementDefinition> children,  XhtmlNode x, String path, boolean showCodeDetails, int indent, ResourceContext rc) throws FHIRException, UnsupportedEncodingException, IOException {
1156    if (children.isEmpty()) {
1157      renderLeaf(res, e, defn, x, false, showCodeDetails, readDisplayHints(defn), path, indent, rc);
1158    } else {
1159      for (PropertyWrapper p : splitExtensions(profile, e.children())) {
1160        if (p.hasValues()) {
1161          ElementDefinition child = getElementDefinition(children, path+"."+p.getName(), p);
1162          if (child != null) {
1163            Map<String, String> displayHints = readDisplayHints(child);
1164            if (!exemptFromRendering(child)) {
1165              List<ElementDefinition> grandChildren = getChildrenForPath(allElements, path+"."+p.getName());
1166            filterGrandChildren(grandChildren, path+"."+p.getName(), p);
1167              if (p.getValues().size() > 0 && child != null) {
1168                if (isPrimitive(child)) {
1169                  XhtmlNode para = x.para();
1170                  String name = p.getName();
1171                  if (name.endsWith("[x]"))
1172                    name = name.substring(0, name.length() - 3);
1173                  if (showCodeDetails || !isDefaultValue(displayHints, p.getValues())) {
1174                    para.b().addText(name);
1175                    para.tx(": ");
1176                    if (renderAsList(child) && p.getValues().size() > 1) {
1177                      XhtmlNode list = x.ul();
1178                      for (BaseWrapper v : p.getValues())
1179                        renderLeaf(res, v, child, list.li(), false, showCodeDetails, displayHints, path, indent, rc);
1180                    } else {
1181                      boolean first = true;
1182                      for (BaseWrapper v : p.getValues()) {
1183                        if (first)
1184                          first = false;
1185                        else
1186                          para.tx(", ");
1187                        renderLeaf(res, v, child, para, false, showCodeDetails, displayHints, path, indent, rc);
1188                      }
1189                    }
1190                  }
1191                } else if (canDoTable(path, p, grandChildren)) {
1192                  x.addTag(getHeader()).addText(Utilities.capitalize(Utilities.camelCase(Utilities.pluralizeMe(p.getName()))));
1193                  XhtmlNode tbl = x.table( "grid");
1194                  XhtmlNode tr = tbl.tr();
1195                  tr.td().tx("-"); // work around problem with empty table rows
1196                  addColumnHeadings(tr, grandChildren);
1197                  for (BaseWrapper v : p.getValues()) {
1198                    if (v != null) {
1199                      tr = tbl.tr();
1200                      tr.td().tx("*"); // work around problem with empty table rows
1201                      addColumnValues(res, tr, grandChildren, v, showCodeDetails, displayHints, path, indent, rc);
1202                    }
1203                  }
1204                } else {
1205                  for (BaseWrapper v : p.getValues()) {
1206                    if (v != null) {
1207                      XhtmlNode bq = x.addTag("blockquote");
1208                      bq.para().b().addText(p.getName());
1209                      generateByProfile(res, profile, v, allElements, child, grandChildren, bq, path+"."+p.getName(), showCodeDetails, indent+1, rc);
1210                    }
1211                  }
1212                }
1213              }
1214            }
1215          }
1216        }
1217      }
1218    }
1219  }
1220
1221  private String getHeader() {
1222    int i = 3;
1223    while (i <= headerLevelContext)
1224      i++;
1225    if (i > 6)
1226      i = 6;
1227    return "h"+Integer.toString(i);
1228  }
1229
1230  private void filterGrandChildren(List<ElementDefinition> grandChildren,  String string, PropertyWrapper prop) {
1231        List<ElementDefinition> toRemove = new ArrayList<ElementDefinition>();
1232        toRemove.addAll(grandChildren);
1233        for (BaseWrapper b : prop.getValues()) {
1234        List<ElementDefinition> list = new ArrayList<ElementDefinition>();
1235                for (ElementDefinition ed : toRemove) {
1236                        PropertyWrapper p = b.getChildByName(tail(ed.getPath()));
1237                        if (p != null && p.hasValues())
1238                                list.add(ed);
1239                }
1240                toRemove.removeAll(list);
1241        }
1242        grandChildren.removeAll(toRemove);
1243  }
1244
1245  private List<PropertyWrapper> splitExtensions(StructureDefinition profile, List<PropertyWrapper> children) throws UnsupportedEncodingException, IOException, FHIRException {
1246    List<PropertyWrapper> results = new ArrayList<PropertyWrapper>();
1247    Map<String, PropertyWrapper> map = new HashMap<String, PropertyWrapper>();
1248    for (PropertyWrapper p : children)
1249      if (p.getName().equals("extension") || p.getName().equals("modifierExtension")) {
1250        // we're going to split these up, and create a property for each url
1251        if (p.hasValues()) {
1252          for (BaseWrapper v : p.getValues()) {
1253            Extension ex  = (Extension) v.getBase();
1254            String url = ex.getUrl();
1255            StructureDefinition ed = context.fetchResource(StructureDefinition.class, url);
1256            if (p.getName().equals("modifierExtension") && ed == null)
1257              throw new DefinitionException("Unknown modifier extension "+url);
1258            PropertyWrapper pe = map.get(p.getName()+"["+url+"]");
1259            if (pe == null) {
1260              if (ed == null) {
1261                if (url.startsWith("http://hl7.org/fhir") && !url.startsWith("http://hl7.org/fhir/us"))
1262                  throw new DefinitionException("unknown extension "+url);
1263                // System.out.println("unknown extension "+url);
1264                pe = new PropertyWrapperDirect(new Property(p.getName()+"["+url+"]", p.getTypeCode(), p.getDefinition(), p.getMinCardinality(), p.getMaxCardinality(), ex));
1265              } else {
1266                ElementDefinition def = ed.getSnapshot().getElement().get(0);
1267                pe = new PropertyWrapperDirect(new Property(p.getName()+"["+url+"]", "Extension", def.getDefinition(), def.getMin(), def.getMax().equals("*") ? Integer.MAX_VALUE : Integer.parseInt(def.getMax()), ex));
1268                ((PropertyWrapperDirect) pe).wrapped.setStructure(ed);
1269              }
1270              results.add(pe);
1271            } else
1272              pe.getValues().add(v);
1273          }
1274        }
1275      } else
1276        results.add(p);
1277    return results;
1278  }
1279
1280  @SuppressWarnings("rawtypes")
1281  private boolean isDefaultValue(Map<String, String> displayHints, List<BaseWrapper> list) throws UnsupportedEncodingException, IOException, FHIRException {
1282    if (list.size() != 1)
1283      return false;
1284    if (list.get(0).getBase() instanceof PrimitiveType)
1285      return isDefault(displayHints, (PrimitiveType) list.get(0).getBase());
1286    else
1287      return false;
1288  }
1289
1290  private boolean isDefault(Map<String, String> displayHints, PrimitiveType primitiveType) {
1291    String v = primitiveType.asStringValue();
1292    if (!Utilities.noString(v) && displayHints.containsKey("default") && v.equals(displayHints.get("default")))
1293        return true;
1294    return false;
1295  }
1296
1297  private boolean exemptFromRendering(ElementDefinition child) {
1298    if (child == null)
1299      return false;
1300    if ("Composition.subject".equals(child.getPath()))
1301      return true;
1302    if ("Composition.section".equals(child.getPath()))
1303      return true;
1304    return false;
1305  }
1306
1307  private boolean renderAsList(ElementDefinition child) {
1308    if (child.getType().size() == 1) {
1309      String t = child.getType().get(0).getWorkingCode();
1310      if (t.equals("Address") || t.equals("Reference"))
1311        return true;
1312    }
1313    return false;
1314  }
1315
1316  private void addColumnHeadings(XhtmlNode tr, List<ElementDefinition> grandChildren) {
1317    for (ElementDefinition e : grandChildren)
1318      tr.td().b().addText(Utilities.capitalize(tail(e.getPath())));
1319  }
1320
1321  private void addColumnValues(ResourceWrapper res, XhtmlNode tr, List<ElementDefinition> grandChildren, BaseWrapper v, boolean showCodeDetails, Map<String, String> displayHints, String path, int indent, ResourceContext rc) throws FHIRException, UnsupportedEncodingException, IOException {
1322    for (ElementDefinition e : grandChildren) {
1323      PropertyWrapper p = v.getChildByName(e.getPath().substring(e.getPath().lastIndexOf(".")+1));
1324      if (p == null || p.getValues().size() == 0 || p.getValues().get(0) == null)
1325        tr.td().tx(" ");
1326      else
1327        renderLeaf(res, p.getValues().get(0), e, tr.td(), false, showCodeDetails, displayHints, path, indent, rc);
1328    }
1329  }
1330
1331  private String tail(String path) {
1332    return path.substring(path.lastIndexOf(".")+1);
1333  }
1334
1335  private boolean canDoTable(String path, PropertyWrapper p, List<ElementDefinition> grandChildren) {
1336    for (ElementDefinition e : grandChildren) {
1337      List<PropertyWrapper> values = getValues(path, p, e);
1338      if (values.size() > 1 || !isPrimitive(e) || !canCollapse(e))
1339        return false;
1340    }
1341    return true;
1342  }
1343
1344  private List<PropertyWrapper> getValues(String path, PropertyWrapper p, ElementDefinition e) {
1345    List<PropertyWrapper> res = new ArrayList<PropertyWrapper>();
1346    for (BaseWrapper v : p.getValues()) {
1347      for (PropertyWrapper g : v.children()) {
1348        if ((path+"."+p.getName()+"."+g.getName()).equals(e.getPath()))
1349          res.add(p);
1350      }
1351    }
1352    return res;
1353  }
1354
1355  private boolean canCollapse(ElementDefinition e) {
1356    // we can collapse any data type
1357    return !e.getType().isEmpty();
1358  }
1359
1360  private boolean isPrimitive(ElementDefinition e) {
1361    //we can tell if e is a primitive because it has types
1362    if (e.getType().isEmpty())
1363      return false;
1364    if (e.getType().size() == 1 && isBase(e.getType().get(0).getWorkingCode()))
1365      return false;
1366    return true;
1367//    return !e.getType().isEmpty()
1368  }
1369
1370  private boolean isBase(String code) {
1371    return code.equals("Element") || code.equals("BackboneElement");
1372  }
1373
1374  private ElementDefinition getElementDefinition(List<ElementDefinition> elements, String path, PropertyWrapper p) {
1375    for (ElementDefinition element : elements)
1376      if (element.getPath().equals(path))
1377        return element;
1378    if (path.endsWith("\"]") && p.getStructure() != null)
1379      return p.getStructure().getSnapshot().getElement().get(0);
1380    return null;
1381  }
1382
1383  private void renderLeaf(ResourceWrapper res, BaseWrapper ew, ElementDefinition defn, XhtmlNode x, boolean title, boolean showCodeDetails, Map<String, String> displayHints, String path, int indent, ResourceContext rc) throws FHIRException, UnsupportedEncodingException, IOException {
1384    if (ew == null)
1385      return;
1386
1387
1388    Base e = ew.getBase();
1389
1390    if (e instanceof StringType)
1391      x.addText(((StringType) e).getValue());
1392    else if (e instanceof CodeType)
1393      x.addText(((CodeType) e).getValue());
1394    else if (e instanceof IdType)
1395      x.addText(((IdType) e).getValue());
1396    else if (e instanceof Extension)
1397      return;
1398    else if (e instanceof InstantType)
1399      x.addText(((InstantType) e).toHumanDisplay());
1400    else if (e instanceof DateTimeType) {
1401      if (e.hasPrimitiveValue())
1402        x.addText(((DateTimeType) e).toHumanDisplay());
1403    } else if (e instanceof Base64BinaryType)
1404      x.addText(new Base64().encodeAsString(((Base64BinaryType) e).getValue()));
1405    else if (e instanceof org.hl7.fhir.r5.model.DateType)
1406      x.addText(((org.hl7.fhir.r5.model.DateType) e).toHumanDisplay());
1407    else if (e instanceof Enumeration) {
1408      Object ev = ((Enumeration<?>) e).getValue();
1409                        x.addText(ev == null ? "" : ev.toString()); // todo: look up a display name if there is one
1410    } else if (e instanceof BooleanType)
1411      x.addText(((BooleanType) e).getValue().toString());
1412    else if (e instanceof CodeableConcept) {
1413      renderCodeableConcept((CodeableConcept) e, x, showCodeDetails);
1414    } else if (e instanceof Coding) {
1415      renderCoding((Coding) e, x, showCodeDetails);
1416    } else if (e instanceof Annotation) {
1417      renderAnnotation((Annotation) e, x);
1418    } else if (e instanceof Identifier) {
1419      renderIdentifier((Identifier) e, x);
1420    } else if (e instanceof org.hl7.fhir.r5.model.IntegerType) {
1421      x.addText(Integer.toString(((org.hl7.fhir.r5.model.IntegerType) e).getValue()));
1422    } else if (e instanceof org.hl7.fhir.r5.model.DecimalType) {
1423      x.addText(((org.hl7.fhir.r5.model.DecimalType) e).getValue().toString());
1424    } else if (e instanceof HumanName) {
1425      renderHumanName((HumanName) e, x);
1426    } else if (e instanceof SampledData) {
1427      renderSampledData((SampledData) e, x);
1428    } else if (e instanceof Address) {
1429      renderAddress((Address) e, x);
1430    } else if (e instanceof ContactPoint) {
1431      renderContactPoint((ContactPoint) e, x);
1432    } else if (e instanceof UriType) {
1433      renderUri((UriType) e, x, defn.getPath(), rc != null && rc.resourceResource != null ? rc.resourceResource.getId() : null);
1434    } else if (e instanceof Timing) {
1435      renderTiming((Timing) e, x);
1436    } else if (e instanceof Range) {
1437      renderRange((Range) e, x);
1438    } else if (e instanceof Quantity) {
1439      renderQuantity((Quantity) e, x, showCodeDetails);
1440    } else if (e instanceof Ratio) {
1441      renderQuantity(((Ratio) e).getNumerator(), x, showCodeDetails);
1442      x.tx("/");
1443      renderQuantity(((Ratio) e).getDenominator(), x, showCodeDetails);
1444    } else if (e instanceof Period) {
1445      Period p = (Period) e;
1446      x.addText(!p.hasStart() ? "??" : p.getStartElement().toHumanDisplay());
1447      x.tx(" --> ");
1448      x.addText(!p.hasEnd() ? "(ongoing)" : p.getEndElement().toHumanDisplay());
1449    } else if (e instanceof Reference) {
1450      Reference r = (Reference) e;
1451      XhtmlNode c = x;
1452      ResourceWithReference tr = null;
1453      if (r.hasReferenceElement()) {
1454        tr = resolveReference(res, r.getReference(), rc);
1455        
1456        if (!r.getReference().startsWith("#")) {
1457          if (tr != null && tr.getReference() != null)
1458            c = x.ah(tr.getReference());
1459          else
1460            c = x.ah(r.getReference());
1461        }
1462      }
1463      // what to display: if text is provided, then that. if the reference was resolved, then show the generated narrative
1464      if (r.hasDisplayElement()) {
1465        c.addText(r.getDisplay());
1466        if (tr != null && tr.getResource() != null) {
1467          c.tx(". Generated Summary: ");
1468          generateResourceSummary(c, tr.getResource(), true, r.getReference().startsWith("#"), rc);
1469        }
1470      } else if (tr != null && tr.getResource() != null) {
1471        generateResourceSummary(c, tr.getResource(), r.getReference().startsWith("#"), r.getReference().startsWith("#"), rc);
1472      } else {
1473        c.addText(r.getReference());
1474      }
1475    } else if (e instanceof Resource) {
1476      return;
1477    } else if (e instanceof ElementDefinition) {
1478      x.tx("todo-bundle");
1479    } else if (e != null && !(e instanceof Attachment) && !(e instanceof Narrative) && !(e instanceof Meta)) {
1480      StructureDefinition sd = context.fetchTypeDefinition(e.fhirType());
1481      if (sd == null)
1482        throw new NotImplementedException("type "+e.getClass().getName()+" not handled yet, and no structure found");
1483      else
1484        generateByProfile(res, sd, ew, sd.getSnapshot().getElement(), sd.getSnapshot().getElementFirstRep(),
1485            getChildrenForPath(sd.getSnapshot().getElement(), sd.getSnapshot().getElementFirstRep().getPath()), x, path, showCodeDetails, indent + 1, rc);
1486    }
1487  }
1488
1489  private boolean displayLeaf(ResourceWrapper res, BaseWrapper ew, ElementDefinition defn, XhtmlNode x, String name, boolean showCodeDetails, ResourceContext rc) throws FHIRException, UnsupportedEncodingException, IOException {
1490    if (ew == null)
1491      return false;
1492    Base e = ew.getBase();
1493    if (e == null)
1494      return false;
1495
1496    Map<String, String> displayHints = readDisplayHints(defn);
1497
1498    if (name.endsWith("[x]"))
1499      name = name.substring(0, name.length() - 3);
1500
1501    if (!showCodeDetails && e instanceof PrimitiveType && isDefault(displayHints, ((PrimitiveType) e)))
1502        return false;
1503
1504    if (e instanceof StringType) {
1505      x.addText(name+": "+((StringType) e).getValue());
1506      return true;
1507    } else if (e instanceof CodeType) {
1508      x.addText(name+": "+((CodeType) e).getValue());
1509      return true;
1510    } else if (e instanceof IdType) {
1511      x.addText(name+": "+((IdType) e).getValue());
1512      return true;
1513    } else if (e instanceof UriType) {
1514      x.addText(name+": "+((UriType) e).getValue());
1515      return true;
1516    } else if (e instanceof DateTimeType) {
1517      x.addText(name+": "+((DateTimeType) e).toHumanDisplay());
1518      return true;
1519    } else if (e instanceof InstantType) {
1520      x.addText(name+": "+((InstantType) e).toHumanDisplay());
1521      return true;
1522    } else if (e instanceof Extension) {
1523//      x.tx("Extensions: todo");
1524      return false;
1525    } else if (e instanceof org.hl7.fhir.r5.model.DateType) {
1526      x.addText(name+": "+((org.hl7.fhir.r5.model.DateType) e).toHumanDisplay());
1527      return true;
1528    } else if (e instanceof Enumeration) {
1529      x.addText(((Enumeration<?>) e).getValue().toString()); // todo: look up a display name if there is one
1530      return true;
1531    } else if (e instanceof BooleanType) {
1532      if (((BooleanType) e).getValue()) {
1533        x.addText(name);
1534          return true;
1535      }
1536    } else if (e instanceof CodeableConcept) {
1537      renderCodeableConcept((CodeableConcept) e, x, showCodeDetails);
1538      return true;
1539    } else if (e instanceof Coding) {
1540      renderCoding((Coding) e, x, showCodeDetails);
1541      return true;
1542    } else if (e instanceof Annotation) {
1543      renderAnnotation((Annotation) e, x, showCodeDetails);
1544      return true;
1545    } else if (e instanceof org.hl7.fhir.r5.model.IntegerType) {
1546      x.addText(Integer.toString(((org.hl7.fhir.r5.model.IntegerType) e).getValue()));
1547      return true;
1548    } else if (e instanceof org.hl7.fhir.r5.model.DecimalType) {
1549      x.addText(((org.hl7.fhir.r5.model.DecimalType) e).getValue().toString());
1550      return true;
1551    } else if (e instanceof Identifier) {
1552      renderIdentifier((Identifier) e, x);
1553      return true;
1554    } else if (e instanceof HumanName) {
1555      renderHumanName((HumanName) e, x);
1556      return true;
1557    } else if (e instanceof SampledData) {
1558      renderSampledData((SampledData) e, x);
1559      return true;
1560    } else if (e instanceof Address) {
1561      renderAddress((Address) e, x);
1562      return true;
1563    } else if (e instanceof ContactPoint) {
1564      renderContactPoint((ContactPoint) e, x);
1565      return true;
1566    } else if (e instanceof Timing) {
1567      renderTiming((Timing) e, x);
1568      return true;
1569    } else if (e instanceof Quantity) {
1570      renderQuantity((Quantity) e, x, showCodeDetails);
1571      return true;
1572    } else if (e instanceof Ratio) {
1573      renderQuantity(((Ratio) e).getNumerator(), x, showCodeDetails);
1574      x.tx("/");
1575      renderQuantity(((Ratio) e).getDenominator(), x, showCodeDetails);
1576      return true;
1577    } else if (e instanceof Period) {
1578      Period p = (Period) e;
1579      x.addText(name+": ");
1580      x.addText(!p.hasStart() ? "??" : p.getStartElement().toHumanDisplay());
1581      x.tx(" --> ");
1582      x.addText(!p.hasEnd() ? "(ongoing)" : p.getEndElement().toHumanDisplay());
1583      return true;
1584    } else if (e instanceof Reference) {
1585      Reference r = (Reference) e;
1586      if (r.hasDisplayElement())
1587        x.addText(r.getDisplay());
1588      else if (r.hasReferenceElement()) {
1589        ResourceWithReference tr = resolveReference(res, r.getReference(), rc);
1590        x.addText(tr == null ? r.getReference() : "????"); // getDisplayForReference(tr.getReference()));
1591      } else
1592        x.tx("??");
1593      return true;
1594    } else if (e instanceof Narrative) {
1595      return false;
1596    } else if (e instanceof Resource) {
1597      return false;
1598    } else if (e instanceof ContactDetail) {
1599      return false;
1600    } else if (e instanceof Range) {
1601      return false;
1602    } else if (e instanceof Meta) {
1603      return false;
1604    } else if (e instanceof Dosage) {
1605      return false;
1606    } else if (e instanceof Signature) {
1607      return false;
1608    } else if (e instanceof UsageContext) {
1609      return false;
1610    } else if (e instanceof RelatedArtifact) {
1611      return false;
1612    } else if (e instanceof ElementDefinition) {
1613      return false;
1614    } else if (!(e instanceof Attachment))
1615      throw new NotImplementedException("type "+e.getClass().getName()+" not handled yet");
1616    return false;
1617  }
1618
1619
1620  private Map<String, String> readDisplayHints(ElementDefinition defn) throws DefinitionException {
1621    Map<String, String> hints = new HashMap<String, String>();
1622    if (defn != null) {
1623      String displayHint = ToolingExtensions.getDisplayHint(defn);
1624      if (!Utilities.noString(displayHint)) {
1625        String[] list = displayHint.split(";");
1626        for (String item : list) {
1627          String[] parts = item.split(":");
1628          if (parts.length != 2)
1629            throw new DefinitionException("error reading display hint: '"+displayHint+"'");
1630          hints.put(parts[0].trim(), parts[1].trim());
1631        }
1632      }
1633    }
1634    return hints;
1635  }
1636
1637  public static String displayPeriod(Period p) {
1638    String s = !p.hasStart() ? "??" : p.getStartElement().toHumanDisplay();
1639    s = s + " --> ";
1640    return s + (!p.hasEnd() ? "(ongoing)" : p.getEndElement().toHumanDisplay());
1641  }
1642
1643  private void generateResourceSummary(XhtmlNode x, ResourceWrapper res, boolean textAlready, boolean showCodeDetails, ResourceContext rc) throws FHIRException, UnsupportedEncodingException, IOException {
1644    if (!textAlready) {
1645      XhtmlNode div = res.getNarrative();
1646      if (div != null) {
1647        if (div.allChildrenAreText())
1648          x.getChildNodes().addAll(div.getChildNodes());
1649        if (div.getChildNodes().size() == 1 && div.getChildNodes().get(0).allChildrenAreText())
1650          x.getChildNodes().addAll(div.getChildNodes().get(0).getChildNodes());
1651      }
1652      x.tx("Generated Summary: ");
1653    }
1654    String path = res.getName();
1655    StructureDefinition profile = context.fetchResource(StructureDefinition.class, path);
1656    if (profile == null)
1657      x.tx("unknown resource " +path);
1658    else {
1659      boolean firstElement = true;
1660      boolean last = false;
1661      for (PropertyWrapper p : res.children()) {
1662        ElementDefinition child = getElementDefinition(profile.getSnapshot().getElement(), path+"."+p.getName(), p);
1663        if (p.getValues().size() > 0 && p.getValues().get(0) != null && child != null && isPrimitive(child) && includeInSummary(child)) {
1664          if (firstElement)
1665            firstElement = false;
1666          else if (last)
1667            x.tx("; ");
1668          boolean first = true;
1669          last = false;
1670          for (BaseWrapper v : p.getValues()) {
1671            if (first)
1672              first = false;
1673            else if (last)
1674              x.tx(", ");
1675            last = displayLeaf(res, v, child, x, p.getName(), showCodeDetails, rc) || last;
1676          }
1677        }
1678      }
1679    }
1680  }
1681
1682
1683  private boolean includeInSummary(ElementDefinition child) {
1684    if (child.getIsModifier())
1685      return true;
1686    if (child.getMustSupport())
1687      return true;
1688    if (child.getType().size() == 1) {
1689      String t = child.getType().get(0).getWorkingCode();
1690      if (t.equals("Address") || t.equals("Contact") || t.equals("Reference") || t.equals("Uri") || t.equals("Url") || t.equals("Canonical"))
1691        return false;
1692    }
1693    return true;
1694  }
1695
1696  private ResourceWithReference resolveReference(ResourceWrapper res, String url, ResourceContext rc) {
1697    if (url == null)
1698      return null;
1699    if (url.startsWith("#")) {
1700      for (ResourceWrapper r : res.getContained()) {
1701        if (r.getId().equals(url.substring(1)))
1702          return new ResourceWithReference(null, r);
1703      }
1704      return null;
1705    }
1706    
1707    if (rc!=null) {
1708      Resource bundleResource = rc.resolve(url);
1709      if (bundleResource!=null) {
1710        String bundleUrl = "#" + bundleResource.getResourceType().name().toLowerCase() + "_" + bundleResource.getId(); 
1711        return new ResourceWithReference(bundleUrl, new ResourceWrapperDirect(bundleResource));
1712      }
1713    }
1714
1715    Resource ae = context.fetchResource(null, url);
1716    if (ae != null)
1717      return new ResourceWithReference(url, new ResourceWrapperDirect(ae));
1718    else if (resolver != null) {
1719      return resolver.resolve(url);
1720    } else
1721      return null;
1722  }
1723
1724  private void renderCodeableConcept(CodeableConcept cc, XhtmlNode x, boolean showCodeDetails) {
1725    String s = cc.getText();
1726    if (Utilities.noString(s)) {
1727      for (Coding c : cc.getCoding()) {
1728        if (c.hasDisplayElement()) {
1729          s = c.getDisplay();
1730          break;
1731        }
1732      }
1733    }
1734    if (Utilities.noString(s)) {
1735      // still? ok, let's try looking it up
1736      for (Coding c : cc.getCoding()) {
1737        if (c.hasCodeElement() && c.hasSystemElement()) {
1738          s = lookupCode(c.getSystem(), c.getCode());
1739          if (!Utilities.noString(s))
1740            break;
1741        }
1742      }
1743    }
1744
1745    if (Utilities.noString(s)) {
1746      if (cc.getCoding().isEmpty())
1747        s = "";
1748      else
1749        s = cc.getCoding().get(0).getCode();
1750    }
1751
1752    if (showCodeDetails) {
1753      x.addText(s+" ");
1754      XhtmlNode sp = x.span("background: LightGoldenRodYellow", null);
1755      sp.tx("(Details ");
1756      boolean first = true;
1757      for (Coding c : cc.getCoding()) {
1758        if (first) {
1759          sp.tx(": ");
1760          first = false;
1761        } else
1762          sp.tx("; ");
1763        sp.tx("{"+describeSystem(c.getSystem())+" code '"+c.getCode()+"' = '"+lookupCode(c.getSystem(), c.getCode())+(c.hasDisplay() ? "', given as '"+c.getDisplay()+"'}" : ""));
1764      }
1765      sp.tx(")");
1766    } else {
1767
1768    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
1769    for (Coding c : cc.getCoding()) {
1770      if (c.hasCodeElement() && c.hasSystemElement()) {
1771        b.append("{"+c.getSystem()+" "+c.getCode()+"}");
1772      }
1773    }
1774
1775    x.span(null, "Codes: "+b.toString()).addText(s);
1776    }
1777  }
1778
1779  private void renderAnnotation(Annotation a, XhtmlNode x, boolean showCodeDetails) throws FHIRException {
1780    StringBuilder s = new StringBuilder();
1781    if (a.hasAuthor()) {
1782      s.append("Author: ");
1783
1784      if (a.hasAuthorReference())
1785        s.append(a.getAuthorReference().getReference());
1786      else if (a.hasAuthorStringType())
1787        s.append(a.getAuthorStringType().getValue());
1788    }
1789
1790
1791    if (a.hasTimeElement()) {
1792      if (s.length() > 0)
1793        s.append("; ");
1794
1795      s.append("Made: ").append(a.getTimeElement().toHumanDisplay());
1796    }
1797
1798    if (a.hasText()) {
1799      if (s.length() > 0)
1800        s.append("; ");
1801
1802      s.append("Annotation: ").append(a.getText());
1803    }
1804
1805    x.addText(s.toString());
1806  }
1807
1808  public String describeCoding(List<Coding> list, boolean showCodeDetails) {
1809    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
1810    for (Coding c : list) {
1811      b.append(describeCoding(c, showCodeDetails));
1812    }
1813    return b.toString();
1814  }
1815  
1816  public String describeCoding(Coding c, boolean showCodeDetails) {
1817    String s = "";
1818    if (c.hasDisplayElement())
1819      s = c.getDisplay();
1820    if (Utilities.noString(s))
1821      s = lookupCode(c.getSystem(), c.getCode());
1822
1823    if (Utilities.noString(s))
1824      s = c.getCode();
1825
1826    if (showCodeDetails) {
1827      return s+" (Details: "+describeSystem(c.getSystem())+" code "+c.getCode()+" = '"+lookupCode(c.getSystem(), c.getCode())+"', stated as '"+c.getDisplay()+"')";
1828    } else
1829      return "<span title=\"{"+c.getSystem()+" "+c.getCode()+"}\">"+Utilities.escapeXml(s)+"</span>";
1830  }
1831
1832  private void renderCoding(Coding c, XhtmlNode x, boolean showCodeDetails) {
1833    String s = "";
1834    if (c.hasDisplayElement())
1835      s = c.getDisplay();
1836    if (Utilities.noString(s))
1837      s = lookupCode(c.getSystem(), c.getCode());
1838
1839    if (Utilities.noString(s))
1840      s = c.getCode();
1841
1842    if (showCodeDetails) {
1843      x.addText(s+" (Details: "+describeSystem(c.getSystem())+" code "+c.getCode()+" = '"+lookupCode(c.getSystem(), c.getCode())+"', stated as '"+c.getDisplay()+"')");
1844    } else
1845      x.span(null, "{"+c.getSystem()+" "+c.getCode()+"}").addText(s);
1846  }
1847
1848  public static String describeSystem(String system) {
1849    if (system == null)
1850      return "[not stated]";
1851    if (system.equals("http://loinc.org"))
1852      return "LOINC";
1853    if (system.startsWith("http://snomed.info"))
1854      return "SNOMED CT";
1855    if (system.equals("http://www.nlm.nih.gov/research/umls/rxnorm"))
1856      return "RxNorm";
1857    if (system.equals("http://hl7.org/fhir/sid/icd-9"))
1858      return "ICD-9";
1859    if (system.equals("http://dicom.nema.org/resources/ontology/DCM"))
1860      return "DICOM";
1861    if (system.equals("http://unitsofmeasure.org"))
1862      return "UCUM";
1863
1864    return system;
1865  }
1866
1867  private String lookupCode(String system, String code) {
1868    ValidationResult t = context.validateCode(terminologyServiceOptions , system, code, null);
1869
1870    if (t != null && t.getDisplay() != null)
1871        return t.getDisplay();
1872    else
1873      return code;
1874
1875  }
1876
1877  private ConceptDefinitionComponent findCode(String code, List<ConceptDefinitionComponent> list) {
1878    for (ConceptDefinitionComponent t : list) {
1879      if (code.equals(t.getCode()))
1880        return t;
1881      ConceptDefinitionComponent c = findCode(code, t.getConcept());
1882      if (c != null)
1883        return c;
1884    }
1885    return null;
1886  }
1887
1888  public String displayCodeableConcept(CodeableConcept cc) {
1889    String s = cc.getText();
1890    if (Utilities.noString(s)) {
1891      for (Coding c : cc.getCoding()) {
1892        if (c.hasDisplayElement()) {
1893          s = c.getDisplay();
1894          break;
1895        }
1896      }
1897    }
1898    if (Utilities.noString(s)) {
1899      // still? ok, let's try looking it up
1900      for (Coding c : cc.getCoding()) {
1901        if (c.hasCode() && c.hasSystem()) {
1902          s = lookupCode(c.getSystem(), c.getCode());
1903          if (!Utilities.noString(s))
1904            break;
1905        }
1906      }
1907    }
1908
1909    if (Utilities.noString(s)) {
1910      if (cc.getCoding().isEmpty())
1911        s = "";
1912      else
1913        s = cc.getCoding().get(0).getCode();
1914    }
1915    return s;
1916  }
1917
1918  private void renderIdentifier(Identifier ii, XhtmlNode x) {
1919    x.addText(displayIdentifier(ii));
1920  }
1921
1922  private void renderTiming(Timing s, XhtmlNode x) throws FHIRException {
1923    x.addText(displayTiming(s));
1924  }
1925
1926  private void renderQuantity(Quantity q, XhtmlNode x, boolean showCodeDetails) {
1927    if (q.hasComparator())
1928      x.addText(q.getComparator().toCode());
1929    x.addText(q.getValue().toString());
1930    if (q.hasUnit())
1931      x.tx(" "+q.getUnit());
1932    else if (q.hasCode())
1933      x.tx(" "+q.getCode());
1934    if (showCodeDetails && q.hasCode()) {
1935      x.span("background: LightGoldenRodYellow", null).tx(" (Details: "+describeSystem(q.getSystem())+" code "+q.getCode()+" = '"+lookupCode(q.getSystem(), q.getCode())+"')");
1936    }
1937  }
1938
1939  private void renderRange(Range q, XhtmlNode x) {
1940    if (q.hasLow())
1941      x.addText(q.getLow().getValue().toString());
1942    else
1943      x.tx("?");
1944    x.tx("-");
1945    if (q.hasHigh())
1946      x.addText(q.getHigh().getValue().toString());
1947    else
1948      x.tx("?");
1949    if (q.getLow().hasUnit())
1950      x.tx(" "+q.getLow().getUnit());
1951  }
1952
1953  public String displayRange(Range q) {
1954    StringBuilder b = new StringBuilder();
1955    if (q.hasLow())
1956      b.append(q.getLow().getValue().toString());
1957    else
1958      b.append("?");
1959    b.append("-");
1960    if (q.hasHigh())
1961      b.append(q.getHigh().getValue().toString());
1962    else
1963      b.append("?");
1964    if (q.getLow().hasUnit())
1965      b.append(" "+q.getLow().getUnit());
1966    return b.toString();
1967  }
1968
1969  private void renderHumanName(HumanName name, XhtmlNode x) {
1970    x.addText(displayHumanName(name));
1971  }
1972
1973  private void renderAnnotation(Annotation annot, XhtmlNode x) {
1974    x.addText(annot.getText());
1975  }
1976
1977  private void renderAddress(Address address, XhtmlNode x) {
1978    x.addText(displayAddress(address));
1979  }
1980
1981  private void renderContactPoint(ContactPoint contact, XhtmlNode x) {
1982    x.addText(displayContactPoint(contact));
1983  }
1984
1985  private void renderUri(UriType uri, XhtmlNode x, String path, String id) {
1986    String url = uri.getValue();
1987    if (isCanonical(path)) {
1988      MetadataResource mr = context.fetchResource(null, url);
1989      if (mr != null) {
1990        if (path.startsWith(mr.fhirType()+".") && mr.getId().equals(id)) {
1991          url = null; // don't link to self whatever
1992        } else if (mr.hasUserData("path"))
1993          url = mr.getUserString("path");
1994      } else if (!canonicalUrlsAsLinks)
1995        url = null;
1996    }
1997    if (url == null)
1998      x.b().tx(uri.getValue());
1999    else if (uri.getValue().startsWith("mailto:"))
2000      x.ah(uri.getValue()).addText(uri.getValue().substring(7));
2001    else
2002      x.ah(uri.getValue()).addText(uri.getValue());
2003  }
2004
2005  private boolean isCanonical(String path) {
2006    if (!path.endsWith(".url")) 
2007      return false;
2008    StructureDefinition sd = context.fetchTypeDefinition(path.substring(0, path.length()-4));
2009    if (sd == null)
2010      return false;
2011    if (Utilities.existsInList(path.substring(0, path.length()-4), "CapabilityStatement", "StructureDefinition", "ImplementationGuide", "SearchParameter", "MessageDefinition", "OperationDefinition", "CompartmentDefinition", "StructureMap", "GraphDefinition", 
2012        "ExampleScenario", "CodeSystem", "ValueSet", "ConceptMap", "NamingSystem", "TerminologyCapabilities"))
2013      return true;
2014    return sd.getBaseDefinitionElement().hasExtension("http://hl7.org/fhir/StructureDefinition/structuredefinition-codegen-super");
2015  }
2016
2017  private void renderSampledData(SampledData sampledData, XhtmlNode x) {
2018    x.addText(displaySampledData(sampledData));
2019  }
2020
2021  private String displaySampledData(SampledData s) {
2022    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
2023    if (s.hasOrigin())
2024      b.append("Origin: "+displayQuantity(s.getOrigin()));
2025
2026    if (s.hasPeriod())
2027      b.append("Period: "+s.getPeriod().toString());
2028
2029    if (s.hasFactor())
2030      b.append("Factor: "+s.getFactor().toString());
2031
2032    if (s.hasLowerLimit())
2033      b.append("Lower: "+s.getLowerLimit().toString());
2034
2035    if (s.hasUpperLimit())
2036      b.append("Upper: "+s.getUpperLimit().toString());
2037
2038    if (s.hasDimensions())
2039      b.append("Dimensions: "+s.getDimensions());
2040
2041    if (s.hasData())
2042      b.append("Data: "+s.getData());
2043
2044    return b.toString();
2045  }
2046
2047  private String displayQuantity(Quantity q) {
2048    StringBuilder s = new StringBuilder();
2049
2050    s.append("(system = '").append(describeSystem(q.getSystem()))
2051        .append("' code ").append(q.getCode())
2052        .append(" = '").append(lookupCode(q.getSystem(), q.getCode())).append("')");
2053
2054    return s.toString();
2055  }
2056
2057  private String displayTiming(Timing s) throws FHIRException {
2058    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
2059    if (s.hasCode())
2060        b.append("Code: "+displayCodeableConcept(s.getCode()));
2061
2062    if (s.getEvent().size() > 0) {
2063      CommaSeparatedStringBuilder c = new CommaSeparatedStringBuilder();
2064      for (DateTimeType p : s.getEvent()) {
2065        c.append(p.toHumanDisplay());
2066      }
2067      b.append("Events: "+ c.toString());
2068    }
2069
2070    if (s.hasRepeat()) {
2071      TimingRepeatComponent rep = s.getRepeat();
2072      if (rep.hasBoundsPeriod() && rep.getBoundsPeriod().hasStart())
2073        b.append("Starting "+rep.getBoundsPeriod().getStartElement().toHumanDisplay());
2074      if (rep.hasCount())
2075        b.append("Count "+Integer.toString(rep.getCount())+" times");
2076      if (rep.hasDuration())
2077        b.append("Duration "+rep.getDuration().toPlainString()+displayTimeUnits(rep.getPeriodUnit()));
2078
2079      if (rep.hasWhen()) {
2080        String st = "";
2081        if (rep.hasOffset()) {
2082          st = Integer.toString(rep.getOffset())+"min ";
2083        }
2084        b.append("Do "+st);
2085        for (Enumeration<EventTiming> wh : rep.getWhen())
2086          b.append(displayEventCode(wh.getValue()));
2087      } else {
2088        String st = "";
2089        if (!rep.hasFrequency() || (!rep.hasFrequencyMax() && rep.getFrequency() == 1) )
2090          st = "Once";
2091        else {
2092          st = Integer.toString(rep.getFrequency());
2093          if (rep.hasFrequencyMax())
2094            st = st + "-"+Integer.toString(rep.getFrequency());
2095        }
2096        if (rep.hasPeriod()) {
2097        st = st + " per "+rep.getPeriod().toPlainString();
2098        if (rep.hasPeriodMax())
2099          st = st + "-"+rep.getPeriodMax().toPlainString();
2100                st = st + " "+displayTimeUnits(rep.getPeriodUnit());
2101        }
2102        b.append("Do "+st);
2103      }
2104      if (rep.hasBoundsPeriod() && rep.getBoundsPeriod().hasEnd())
2105        b.append("Until "+rep.getBoundsPeriod().getEndElement().toHumanDisplay());
2106    }
2107    return b.toString();
2108  }
2109
2110  private String displayEventCode(EventTiming when) {
2111    switch (when) {
2112    case C: return "at meals";
2113    case CD: return "at lunch";
2114    case CM: return "at breakfast";
2115    case CV: return "at dinner";
2116    case AC: return "before meals";
2117    case ACD: return "before lunch";
2118    case ACM: return "before breakfast";
2119    case ACV: return "before dinner";
2120    case HS: return "before sleeping";
2121    case PC: return "after meals";
2122    case PCD: return "after lunch";
2123    case PCM: return "after breakfast";
2124    case PCV: return "after dinner";
2125    case WAKE: return "after waking";
2126    default: return "??";
2127    }
2128  }
2129
2130  private String displayTimeUnits(UnitsOfTime units) {
2131        if (units == null)
2132                return "??";
2133    switch (units) {
2134    case A: return "years";
2135    case D: return "days";
2136    case H: return "hours";
2137    case MIN: return "minutes";
2138    case MO: return "months";
2139    case S: return "seconds";
2140    case WK: return "weeks";
2141    default: return "??";
2142    }
2143  }
2144
2145  public static String displayHumanName(HumanName name) {
2146    StringBuilder s = new StringBuilder();
2147    if (name.hasText())
2148      s.append(name.getText());
2149    else {
2150      for (StringType p : name.getGiven()) {
2151        s.append(p.getValue());
2152        s.append(" ");
2153      }
2154      if (name.hasFamily()) {
2155        s.append(name.getFamily());
2156        s.append(" ");
2157      }
2158    }
2159    if (name.hasUse() && name.getUse() != NameUse.USUAL)
2160      s.append("("+name.getUse().toString()+")");
2161    return s.toString();
2162  }
2163
2164  private String displayAddress(Address address) {
2165    StringBuilder s = new StringBuilder();
2166    if (address.hasText())
2167      s.append(address.getText());
2168    else {
2169      for (StringType p : address.getLine()) {
2170        s.append(p.getValue());
2171        s.append(" ");
2172      }
2173      if (address.hasCity()) {
2174        s.append(address.getCity());
2175        s.append(" ");
2176      }
2177      if (address.hasState()) {
2178        s.append(address.getState());
2179        s.append(" ");
2180      }
2181
2182      if (address.hasPostalCode()) {
2183        s.append(address.getPostalCode());
2184        s.append(" ");
2185      }
2186
2187      if (address.hasCountry()) {
2188        s.append(address.getCountry());
2189        s.append(" ");
2190      }
2191    }
2192    if (address.hasUse())
2193      s.append("("+address.getUse().toString()+")");
2194    return s.toString();
2195  }
2196
2197  public static String displayContactPoint(ContactPoint contact) {
2198    StringBuilder s = new StringBuilder();
2199    s.append(describeSystem(contact.getSystem()));
2200    if (Utilities.noString(contact.getValue()))
2201      s.append("-unknown-");
2202    else
2203      s.append(contact.getValue());
2204    if (contact.hasUse())
2205      s.append("("+contact.getUse().toString()+")");
2206    return s.toString();
2207  }
2208
2209  private static String describeSystem(ContactPointSystem system) {
2210    if (system == null)
2211      return "";
2212    switch (system) {
2213    case PHONE: return "ph: ";
2214    case FAX: return "fax: ";
2215    default:
2216      return "";
2217    }
2218  }
2219
2220  private String displayIdentifier(Identifier ii) {
2221    String s = Utilities.noString(ii.getValue()) ? "??" : ii.getValue();
2222
2223    if (ii.hasType()) {
2224        if (ii.getType().hasText())
2225                s = ii.getType().getText()+" = "+s;
2226        else if (ii.getType().hasCoding() && ii.getType().getCoding().get(0).hasDisplay())
2227                s = ii.getType().getCoding().get(0).getDisplay()+" = "+s;
2228        else if (ii.getType().hasCoding() && ii.getType().getCoding().get(0).hasCode())
2229                s = lookupCode(ii.getType().getCoding().get(0).getSystem(), ii.getType().getCoding().get(0).getCode())+" = "+s;
2230    }
2231
2232    if (ii.hasUse())
2233      s = s + " ("+ii.getUse().toString()+")";
2234    return s;
2235  }
2236
2237  private List<ElementDefinition> getChildrenForPath(List<ElementDefinition> elements, String path) throws DefinitionException {
2238    // do we need to do a name reference substitution?
2239    for (ElementDefinition e : elements) {
2240      if (e.getPath().equals(path) && e.hasContentReference()) {
2241        String ref = e.getContentReference();
2242        ElementDefinition t = null;
2243        // now, resolve the name
2244        for (ElementDefinition e1 : elements) {
2245                if (ref.equals("#"+e1.getId()))
2246                        t = e1;
2247        }
2248        if (t == null)
2249                throw new DefinitionException("Unable to resolve content reference "+ref+" trying to resolve "+path);
2250        path = t.getPath();
2251        break;
2252      }
2253    }
2254
2255    List<ElementDefinition> results = new ArrayList<ElementDefinition>();
2256    for (ElementDefinition e : elements) {
2257      if (e.getPath().startsWith(path+".") && !e.getPath().substring(path.length()+1).contains("."))
2258        results.add(e);
2259    }
2260    return results;
2261  }
2262
2263
2264  public boolean generate(ResourceContext rcontext, ConceptMap cm) throws FHIRFormatError, DefinitionException, IOException {
2265    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
2266    x.h2().addText(cm.getName()+" ("+cm.getUrl()+")");
2267
2268    XhtmlNode p = x.para();
2269    p.tx("Mapping from ");
2270    if (cm.hasSource())
2271      AddVsRef(rcontext, cm.getSource().primitiveValue(), p);
2272    else
2273      p.tx("(not specified)");
2274    p.tx(" to ");
2275    if (cm.hasTarget())
2276      AddVsRef(rcontext, cm.getTarget().primitiveValue(), p);
2277    else 
2278      p.tx("(not specified)");
2279
2280    p = x.para();
2281    if (cm.getExperimental())
2282      p.addText(Utilities.capitalize(cm.getStatus().toString())+" (not intended for production usage). ");
2283    else
2284      p.addText(Utilities.capitalize(cm.getStatus().toString())+". ");
2285    p.tx("Published on "+(cm.hasDate() ? cm.getDateElement().toHumanDisplay() : "??")+" by "+cm.getPublisher());
2286    if (!cm.getContact().isEmpty()) {
2287      p.tx(" (");
2288      boolean firsti = true;
2289      for (ContactDetail ci : cm.getContact()) {
2290        if (firsti)
2291          firsti = false;
2292        else
2293          p.tx(", ");
2294        if (ci.hasName())
2295          p.addText(ci.getName()+": ");
2296        boolean first = true;
2297        for (ContactPoint c : ci.getTelecom()) {
2298          if (first)
2299            first = false;
2300          else
2301            p.tx(", ");
2302          addTelecom(p, c);
2303        }
2304      }
2305      p.tx(")");
2306    }
2307    p.tx(". ");
2308    p.addText(cm.getCopyright());
2309    if (!Utilities.noString(cm.getDescription()))
2310      addMarkdown(x, cm.getDescription());
2311
2312    x.br();
2313    CodeSystem cs = context.fetchCodeSystem("http://hl7.org/fhir/concept-map-relationship");
2314    if (cs == null)
2315      cs = context.fetchCodeSystem("http://hl7.org/fhir/ValueSet/concept-map-equivalence");
2316    String eqpath = cs == null ? null : cs.getUserString("path");
2317
2318    for (ConceptMapGroupComponent grp : cm.getGroup()) {
2319      String src = grp.getSource();
2320      boolean comment = false;
2321      boolean ok = true;
2322    Map<String, HashSet<String>> sources = new HashMap<String, HashSet<String>>();
2323    Map<String, HashSet<String>> targets = new HashMap<String, HashSet<String>>();
2324      sources.put("code", new HashSet<String>());
2325    targets.put("code", new HashSet<String>());
2326      SourceElementComponent cc = grp.getElement().get(0);
2327      String dst = grp.getTarget();
2328      sources.get("code").add(grp.getSource());
2329      targets.get("code").add(grp.getTarget());
2330      for (SourceElementComponent ccl : grp.getElement()) {
2331        ok = ok && ccl.getTarget().size() == 1 && ccl.getTarget().get(0).getDependsOn().isEmpty() && ccl.getTarget().get(0).getProduct().isEmpty();
2332        for (TargetElementComponent ccm : ccl.getTarget()) {
2333                comment = comment || !Utilities.noString(ccm.getComment());
2334                for (OtherElementComponent d : ccm.getDependsOn()) {
2335            if (!sources.containsKey(d.getProperty()))
2336              sources.put(d.getProperty(), new HashSet<String>());
2337            sources.get(d.getProperty()).add(d.getSystem());
2338                }
2339                for (OtherElementComponent d : ccm.getProduct()) {
2340            if (!targets.containsKey(d.getProperty()))
2341              targets.put(d.getProperty(), new HashSet<String>());
2342            targets.get(d.getProperty()).add(d.getSystem());
2343            }
2344
2345                }
2346        }
2347
2348      String display;
2349      if (ok) {
2350        // simple
2351        XhtmlNode tbl = x.table( "grid");
2352        XhtmlNode tr = tbl.tr();
2353        tr.td().b().tx("Source Code");
2354        tr.td().b().tx("Relationship");
2355        tr.td().b().tx("Destination Code");
2356        if (comment)
2357          tr.td().b().tx("Comment");
2358        for (SourceElementComponent ccl : grp.getElement()) {
2359          tr = tbl.tr();
2360          XhtmlNode td = tr.td();
2361          td.addText(ccl.getCode());
2362          display = getDisplayForConcept(grp.getSource(), ccl.getCode());
2363          if (display != null && !isSameCodeAndDisplay(ccl.getCode(), display))
2364            td.tx(" ("+display+")");
2365          TargetElementComponent ccm = ccl.getTarget().get(0);
2366          tr.td().addText(!ccm.hasRelationship() ? "" : ccm.getRelationship().toCode());
2367          td = tr.td();
2368          td.addText(ccm.getCode());
2369          display = getDisplayForConcept(grp.getTarget(), ccm.getCode());
2370          if (display != null && !isSameCodeAndDisplay(ccm.getCode(), display))
2371            td.tx(" ("+display+")");
2372          if (comment)
2373            tr.td().addText(ccm.getComment());
2374        }
2375      } else {
2376        XhtmlNode tbl = x.table( "grid");
2377        XhtmlNode tr = tbl.tr();
2378        XhtmlNode td;
2379        tr.td().colspan(Integer.toString(sources.size())).b().tx("Source Concept Details");
2380        tr.td().b().tx("Relationship");
2381        tr.td().colspan(Integer.toString(targets.size())).b().tx("Destination Concept Details");
2382        if (comment)
2383          tr.td().b().tx("Comment");
2384        tr = tbl.tr();
2385        if (sources.get("code").size() == 1) {
2386          String url = sources.get("code").iterator().next();
2387          renderCSDetailsLink(tr, url);           
2388        } else
2389          tr.td().b().tx("Code");
2390        for (String s : sources.keySet()) {
2391          if (!s.equals("code")) {
2392            if (sources.get(s).size() == 1) {
2393              String url = sources.get(s).iterator().next();
2394              renderCSDetailsLink(tr, url);           
2395            } else
2396              tr.td().b().addText(getDescForConcept(s));
2397          }
2398        }
2399        tr.td();
2400        if (targets.get("code").size() == 1) {
2401          String url = targets.get("code").iterator().next();
2402          renderCSDetailsLink(tr, url);           
2403        } else
2404          tr.td().b().tx("Code");
2405        for (String s : targets.keySet()) {
2406          if (!s.equals("code")) {
2407            if (targets.get(s).size() == 1) {
2408              String url = targets.get(s).iterator().next();
2409              renderCSDetailsLink(tr, url);           
2410            } else
2411              tr.td().b().addText(getDescForConcept(s));
2412          }
2413        }
2414        if (comment)
2415          tr.td();
2416
2417        for (int si = 0; si < grp.getElement().size(); si++) {
2418          SourceElementComponent ccl = grp.getElement().get(si);
2419          boolean slast = si == grp.getElement().size()-1;
2420          boolean first = true;
2421          for (int ti = 0; ti < ccl.getTarget().size(); ti++) {
2422            TargetElementComponent ccm = ccl.getTarget().get(ti);
2423            boolean last = ti == ccl.getTarget().size()-1;
2424            tr = tbl.tr();
2425            td = tr.td();
2426            if (!first && !last)
2427              td.setAttribute("style", "border-top-style: none; border-bottom-style: none");
2428            else if (!first)
2429              td.setAttribute("style", "border-top-style: none");
2430            else if (!last)
2431              td.setAttribute("style", "border-bottom-style: none");
2432            if (first) {
2433              if (sources.get("code").size() == 1)
2434                td.addText(ccl.getCode());
2435              else
2436                td.addText(grp.getSource()+" / "+ccl.getCode());
2437              display = getDisplayForConcept(grp.getSource(), ccl.getCode());
2438              if (display != null)
2439                td.tx(" ("+display+")");
2440            }
2441            for (String s : sources.keySet()) {
2442              if (!s.equals("code")) {
2443                td = tr.td();
2444                if (first) {
2445                  td.addText(getValue(ccm.getDependsOn(), s, sources.get(s).size() != 1));
2446                  display = getDisplay(ccm.getDependsOn(), s);
2447                  if (display != null)
2448                    td.tx(" ("+display+")");
2449                }
2450              }
2451            }
2452            first = false;
2453            if (!ccm.hasRelationship())
2454              tr.td().tx(":"+"("+ConceptMapRelationship.EQUIVALENT.toCode()+")");
2455            else
2456              tr.td().ah(eqpath+"#"+ccm.getRelationship().toCode()).tx(ccm.getRelationship().toCode());
2457            td = tr.td();
2458            if (targets.get("code").size() == 1)
2459              td.addText(ccm.getCode());
2460            else
2461              td.addText(grp.getTarget()+" / "+ccm.getCode());
2462            display = getDisplayForConcept(grp.getTarget(), ccm.getCode());
2463            if (display != null)
2464              td.tx(" ("+display+")");
2465  
2466            for (String s : targets.keySet()) {
2467              if (!s.equals("code")) {
2468                td = tr.td();
2469                td.addText(getValue(ccm.getProduct(), s, targets.get(s).size() != 1));
2470                display = getDisplay(ccm.getProduct(), s);
2471                if (display != null)
2472                  td.tx(" ("+display+")");
2473              }
2474            }
2475            if (comment)
2476              tr.td().addText(ccm.getComment());
2477          }
2478        }
2479      }
2480    }
2481
2482    inject(cm, x, NarrativeStatus.GENERATED);
2483    return true;
2484  }
2485
2486  public void renderCSDetailsLink(XhtmlNode tr, String url) {
2487    CodeSystem cs;
2488    XhtmlNode td;
2489    cs = context.fetchCodeSystem(url);
2490    td = tr.td();
2491    td.b().tx("Code");
2492    td.tx(" from ");
2493    if (cs == null)
2494      td.tx(url);
2495    else
2496      td.ah(cs.getUserString("path")).attribute("title", url).tx(cs.present());
2497  }
2498
2499  private boolean isSameCodeAndDisplay(String code, String display) {
2500    String c = code.replace(" ", "").replace("-", "").toLowerCase();
2501    String d = display.replace(" ", "").replace("-", "").toLowerCase();
2502    return c.equals(d);
2503  }
2504
2505  private void inject(DomainResource r, XhtmlNode x, NarrativeStatus status) {
2506    if (!x.hasAttribute("xmlns"))
2507      x.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
2508    if (r.hasLanguage()) {
2509      x.setAttribute("xml:lang", r.getLanguage());
2510    }
2511    if (!r.hasText() || !r.getText().hasDiv() || r.getText().getDiv().getChildNodes().isEmpty()) {
2512      r.setText(new Narrative());
2513      r.getText().setDiv(x);
2514      r.getText().setStatus(status);
2515    } else {
2516      XhtmlNode n = r.getText().getDiv();
2517      n.hr();
2518      n.getChildNodes().addAll(x.getChildNodes());
2519    }
2520  }
2521
2522  public Element getNarrative(Element er) {
2523    Element txt = XMLUtil.getNamedChild(er, "text");
2524    if (txt == null)
2525      return null;
2526    return XMLUtil.getNamedChild(txt, "div");
2527  }
2528
2529
2530  private void inject(Element er, XhtmlNode x, NarrativeStatus status) {
2531    if (!x.hasAttribute("xmlns"))
2532      x.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
2533    Element txt = XMLUtil.getNamedChild(er, "text");
2534    if (txt == null) {
2535      txt = er.getOwnerDocument().createElementNS(FormatUtilities.FHIR_NS, "text");
2536      Element n = XMLUtil.getFirstChild(er);
2537      while (n != null && (n.getNodeName().equals("id") || n.getNodeName().equals("meta") || n.getNodeName().equals("implicitRules") || n.getNodeName().equals("language")))
2538        n = XMLUtil.getNextSibling(n);
2539      if (n == null)
2540        er.appendChild(txt);
2541      else
2542        er.insertBefore(txt, n);
2543    }
2544    Element st = XMLUtil.getNamedChild(txt, "status");
2545    if (st == null) {
2546      st = er.getOwnerDocument().createElementNS(FormatUtilities.FHIR_NS, "status");
2547      Element n = XMLUtil.getFirstChild(txt);
2548      if (n == null)
2549        txt.appendChild(st);
2550      else
2551        txt.insertBefore(st, n);
2552    }
2553    st.setAttribute("value", status.toCode());
2554    Element div = XMLUtil.getNamedChild(txt, "div");
2555    if (div == null) {
2556      div = er.getOwnerDocument().createElementNS(FormatUtilities.XHTML_NS, "div");
2557      div.setAttribute("xmlns", FormatUtilities.XHTML_NS);
2558      txt.appendChild(div);
2559    }
2560    if (div.hasChildNodes())
2561      div.appendChild(er.getOwnerDocument().createElementNS(FormatUtilities.XHTML_NS, "hr"));
2562    new XhtmlComposer(XhtmlComposer.XML, pretty).compose(div, x);
2563  }
2564
2565  private void inject(org.hl7.fhir.r5.elementmodel.Element er, XhtmlNode x, NarrativeStatus status) throws IOException, FHIRException {
2566    if (!x.hasAttribute("xmlns"))
2567      x.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
2568    org.hl7.fhir.r5.elementmodel.Element txt = er.getNamedChild("text");
2569    if (txt == null) {
2570      txt = new org.hl7.fhir.r5.elementmodel.Element("text", er.getProperty().getChild(null, "text"));
2571      int i = 0;
2572      while (i < er.getChildren().size() && (er.getChildren().get(i).getName().equals("id") || er.getChildren().get(i).getName().equals("meta") || er.getChildren().get(i).getName().equals("implicitRules") || er.getChildren().get(i).getName().equals("language")))
2573        i++;
2574      if (i >= er.getChildren().size())
2575        er.getChildren().add(txt);
2576      else
2577        er.getChildren().add(i, txt);
2578    }
2579    org.hl7.fhir.r5.elementmodel.Element st = txt.getNamedChild("status");
2580    if (st == null) {
2581      st = new org.hl7.fhir.r5.elementmodel.Element("status", txt.getProperty().getChild(null, "status"));
2582      txt.getChildren().add(0, st);
2583    }
2584    st.setValue(status.toCode());
2585    org.hl7.fhir.r5.elementmodel.Element div = txt.getNamedChild("div");
2586    if (div == null) {
2587      div = new org.hl7.fhir.r5.elementmodel.Element("div", txt.getProperty().getChild(null, "div"));
2588      txt.getChildren().add(div);
2589      div.setValue(new XhtmlComposer(XhtmlComposer.XML, pretty).compose(x));
2590    }
2591    div.setXhtml(x);
2592  }
2593
2594  private String getDisplay(List<OtherElementComponent> list, String s) {
2595    for (OtherElementComponent c : list) {
2596      if (s.equals(c.getProperty()))
2597        return getDisplayForConcept(c.getSystem(), c.getValue());
2598    }
2599    return null;
2600  }
2601
2602  private String getDisplayForConcept(String system, String value) {
2603    if (value == null || system == null)
2604      return null;
2605    ValidationResult cl = context.validateCode(terminologyServiceOptions, system, value, null);
2606    return cl == null ? null : cl.getDisplay();
2607  }
2608
2609
2610
2611  private String getDescForConcept(String s) {
2612    if (s.startsWith("http://hl7.org/fhir/v2/element/"))
2613        return "v2 "+s.substring("http://hl7.org/fhir/v2/element/".length());
2614    return s;
2615  }
2616
2617  private String getValue(List<OtherElementComponent> list, String s, boolean withSystem) {
2618    for (OtherElementComponent c : list) {
2619      if (s.equals(c.getProperty()))
2620        if (withSystem)
2621          return c.getSystem()+" / "+c.getValue();
2622        else
2623          return c.getValue();
2624    }
2625    return null;
2626  }
2627
2628  private void addTelecom(XhtmlNode p, ContactPoint c) {
2629    if (c.getSystem() == ContactPointSystem.PHONE) {
2630      p.tx("Phone: "+c.getValue());
2631    } else if (c.getSystem() == ContactPointSystem.FAX) {
2632      p.tx("Fax: "+c.getValue());
2633    } else if (c.getSystem() == ContactPointSystem.EMAIL) {
2634      p.ah( "mailto:"+c.getValue()).addText(c.getValue());
2635    } else if (c.getSystem() == ContactPointSystem.URL) {
2636      if (c.getValue().length() > 30)
2637        p.ah(c.getValue()).addText(c.getValue().substring(0, 30)+"...");
2638      else
2639        p.ah(c.getValue()).addText(c.getValue());
2640    }
2641  }
2642
2643  /**
2644   * This generate is optimised for the FHIR build process itself in as much as it
2645   * generates hyperlinks in the narrative that are only going to be correct for
2646   * the purposes of the build. This is to be reviewed in the future.
2647   *
2648   * @param vs
2649   * @param codeSystems
2650   * @throws IOException
2651   * @throws DefinitionException
2652   * @throws FHIRFormatError
2653   * @throws Exception
2654   */
2655  public boolean generate(ResourceContext rcontext, CodeSystem cs, boolean header, String lang) throws FHIRFormatError, DefinitionException, IOException {
2656    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
2657    boolean hasExtensions = false;
2658    hasExtensions = generateDefinition(x, cs, header, lang);
2659    inject(cs, x, hasExtensions ? NarrativeStatus.EXTENSIONS :  NarrativeStatus.GENERATED);
2660    return true;
2661  }
2662
2663  private boolean generateDefinition(XhtmlNode x, CodeSystem cs, boolean header, String lang) throws FHIRFormatError, DefinitionException, IOException {
2664    boolean hasExtensions = false;
2665
2666    if (header) {
2667      XhtmlNode h = x.h2();
2668      h.addText(cs.hasTitle() ? cs.getTitle() : cs.getName());
2669      addMarkdown(x, cs.getDescription());
2670      if (cs.hasCopyright())
2671        generateCopyright(x, cs, lang);
2672    }
2673
2674    generateProperties(x, cs, lang);
2675    generateFilters(x, cs, lang);
2676    List<UsedConceptMap> maps = new ArrayList<UsedConceptMap>();
2677    hasExtensions = generateCodeSystemContent(x, cs, hasExtensions, maps, lang);
2678
2679    return hasExtensions;
2680  }
2681
2682  private void generateFilters(XhtmlNode x, CodeSystem cs, String lang) {
2683    if (cs.hasFilter()) {
2684      x.para().b().tx(context.translator().translate("xhtml-gen-cs", "Filters", lang));
2685      XhtmlNode tbl = x.table("grid");
2686      XhtmlNode tr = tbl.tr();
2687      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Code", lang));
2688      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Description", lang));
2689      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "operator", lang));
2690      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Value", lang));
2691      for (CodeSystemFilterComponent f : cs.getFilter()) {
2692        tr = tbl.tr();
2693        tr.td().tx(f.getCode());
2694        tr.td().tx(f.getDescription());
2695        XhtmlNode td = tr.td();
2696        for (Enumeration<org.hl7.fhir.r5.model.CodeSystem.FilterOperator> t : f.getOperator())
2697          td.tx(t.asStringValue()+" ");
2698        tr.td().tx(f.getValue());
2699      }
2700    }
2701  }
2702
2703  private void generateProperties(XhtmlNode x, CodeSystem cs, String lang) {
2704    if (cs.hasProperty()) {
2705      boolean hasRendered = false;
2706      for (PropertyComponent p : cs.getProperty()) {
2707        hasRendered = hasRendered || !p.getCode().equals(ToolingExtensions.getPresentation(p, p.getCodeElement()));
2708      }
2709      
2710      x.para().b().tx(context.translator().translate("xhtml-gen-cs", "Properties", lang));
2711      XhtmlNode tbl = x.table("grid");
2712      XhtmlNode tr = tbl.tr();
2713      if (hasRendered) {
2714        tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Name", lang));        
2715      }
2716      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Code", lang));
2717      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "URL", lang));
2718      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Description", lang));
2719      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Type", lang));
2720      for (PropertyComponent p : cs.getProperty()) {
2721        tr = tbl.tr();
2722        if (hasRendered) {
2723          tr.td().tx(ToolingExtensions.getPresentation(p, p.getCodeElement()));          
2724        }
2725        tr.td().tx(p.getCode());
2726        tr.td().tx(p.getUri());
2727        tr.td().tx(p.getDescription());
2728        tr.td().tx(p.hasType() ? p.getType().toCode() : "");
2729      }
2730    }
2731  }
2732
2733  private boolean generateCodeSystemContent(XhtmlNode x, CodeSystem cs, boolean hasExtensions, List<UsedConceptMap> maps, String lang) throws FHIRFormatError, DefinitionException, IOException {
2734    XhtmlNode p = x.para();
2735    if (cs.getContent() == CodeSystemContentMode.COMPLETE)
2736      p.tx(context.translator().translateAndFormat("xhtml-gen-cs", lang, "This code system %s defines the following codes", cs.getUrl())+":");
2737    else if (cs.getContent() == CodeSystemContentMode.EXAMPLE)
2738      p.tx(context.translator().translateAndFormat("xhtml-gen-cs", lang, "This code system %s defines many codes, of which the following are some examples", cs.getUrl())+":");
2739    else if (cs.getContent() == CodeSystemContentMode.FRAGMENT )
2740      p.tx(context.translator().translateAndFormat("xhtml-gen-cs", lang, "This code system %s defines many codes, of which the following are a subset", cs.getUrl())+":");
2741    else if (cs.getContent() == CodeSystemContentMode.NOTPRESENT ) {
2742      p.tx(context.translator().translateAndFormat("xhtml-gen-cs", lang, "This code system %s defines many codes, but they are not represented here", cs.getUrl()));
2743      return false;
2744    }
2745    XhtmlNode t = x.table( "codes");
2746    boolean commentS = false;
2747    boolean deprecated = false;
2748    boolean display = false;
2749    boolean hierarchy = false;
2750    boolean version = false;
2751    List<PropertyComponent> properties = new ArrayList();
2752    for (PropertyComponent cp : cs.getProperty()) {
2753      if (showPropertyInTable(cp)) {
2754        boolean exists = false;
2755        for (ConceptDefinitionComponent c : cs.getConcept()) {
2756          exists = exists || conceptsHaveProperty(c, cp);
2757        }
2758        if (exists) {
2759          properties.add(cp);
2760        }
2761      }
2762    }
2763    for (ConceptDefinitionComponent c : cs.getConcept()) {
2764      commentS = commentS || conceptsHaveComments(c);
2765      deprecated = deprecated || conceptsHaveDeprecated(cs, c);
2766      display = display || conceptsHaveDisplay(c);
2767      version = version || conceptsHaveVersion(c);
2768      hierarchy = hierarchy || c.hasConcept();
2769    }
2770    addMapHeaders(addTableHeaderRowStandard(t, hierarchy, display, true, commentS, version, deprecated, lang, properties), maps);
2771    for (ConceptDefinitionComponent c : cs.getConcept()) {
2772      hasExtensions = addDefineRowToTable(t, c, 0, hierarchy, display, commentS, version, deprecated, maps, cs.getUrl(), cs, lang, properties) || hasExtensions;
2773    }
2774//    if (langs.size() > 0) {
2775//      Collections.sort(langs);
2776//      x.para().b().tx("Additional Language Displays");
2777//      t = x.table( "codes");
2778//      XhtmlNode tr = t.tr();
2779//      tr.td().b().tx("Code");
2780//      for (String lang : langs)
2781//        tr.td().b().addText(describeLang(lang));
2782//      for (ConceptDefinitionComponent c : cs.getConcept()) {
2783//        addLanguageRow(c, t, langs);
2784//      }
2785//    }
2786    return hasExtensions;
2787  }
2788
2789  private boolean conceptsHaveProperty(ConceptDefinitionComponent c, PropertyComponent cp) {
2790    if (CodeSystemUtilities.hasProperty(c, cp.getCode()))
2791      return true;
2792    for (ConceptDefinitionComponent g : c.getConcept())
2793      if (conceptsHaveProperty(g,  cp))
2794        return true;
2795    return false;
2796
2797  }
2798
2799  private boolean showPropertyInTable(PropertyComponent cp) {
2800    if (cp.hasCode()) {
2801      return 
2802        Utilities.existsInList(cp.getUri(), "http://hl7.org/fhir/concept-properties") ||
2803        codeSystemPropList.contains(cp.getUri()) || 
2804        cp.hasExtension(ToolingExtensions.EXT_RENDERED_VALUE);
2805    }
2806    return false;
2807  }
2808
2809  private int countConcepts(List<ConceptDefinitionComponent> list) {
2810    int count = list.size();
2811    for (ConceptDefinitionComponent c : list)
2812      if (c.hasConcept())
2813        count = count + countConcepts(c.getConcept());
2814    return count;
2815  }
2816
2817  private void generateCopyright(XhtmlNode x, CodeSystem cs, String lang) {
2818    XhtmlNode p = x.para();
2819    p.b().tx(context.translator().translate("xhtml-gen-cs", "Copyright Statement:", lang));
2820    smartAddText(p, " " + cs.getCopyright());
2821  }
2822
2823
2824  /**
2825   * This generate is optimised for the FHIR build process itself in as much as it
2826   * generates hyperlinks in the narrative that are only going to be correct for
2827   * the purposes of the build. This is to be reviewed in the future.
2828   *
2829   * @param vs
2830   * @param codeSystems
2831   * @throws FHIRException
2832   * @throws IOException
2833   * @throws Exception
2834   */
2835  public boolean generate(ResourceContext rcontext, ValueSet vs, boolean header) throws FHIRException, IOException {
2836    generate(rcontext, vs, null, header);
2837    return true;
2838  }
2839
2840  public void generate(ResourceContext rcontext, ValueSet vs, ValueSet src, boolean header) throws FHIRException, IOException {
2841    List<UsedConceptMap> maps = findReleventMaps(vs);
2842    
2843    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
2844    boolean hasExtensions;
2845    if (vs.hasExpansion()) {
2846      // for now, we just accept an expansion if there is one
2847      hasExtensions = generateExpansion(x, vs, src, header, maps);
2848    } else {
2849      hasExtensions = generateComposition(rcontext, x, vs, header, maps);
2850    }
2851    inject(vs, x, hasExtensions ? NarrativeStatus.EXTENSIONS :  NarrativeStatus.GENERATED);
2852  }
2853
2854  private List<UsedConceptMap> findReleventMaps(ValueSet vs) throws FHIRException {
2855    List<UsedConceptMap> res = new ArrayList<UsedConceptMap>();
2856    for (MetadataResource md : context.allConformanceResources()) {
2857      if (md instanceof ConceptMap) {
2858        ConceptMap cm = (ConceptMap) md;
2859        if (isSource(vs, cm.getSource())) {
2860          ConceptMapRenderInstructions re = findByTarget(cm.getTarget());
2861          if (re != null) {
2862            ValueSet vst = cm.hasTarget() ? context.fetchResource(ValueSet.class, cm.hasTargetCanonicalType() ? cm.getTargetCanonicalType().getValue() : cm.getTargetUriType().asStringValue()) : null;
2863            res.add(new UsedConceptMap(re, vst == null ? cm.getUserString("path") : vst.getUserString("path"), cm));
2864          }
2865        }
2866      }
2867    }
2868    return res;
2869//    Map<ConceptMap, String> mymaps = new HashMap<ConceptMap, String>();
2870//  for (ConceptMap a : context.findMapsForSource(vs.getUrl())) {
2871//    String url = "";
2872//    ValueSet vsr = context.fetchResource(ValueSet.class, ((Reference) a.getTarget()).getReference());
2873//    if (vsr != null)
2874//      url = (String) vsr.getUserData("filename");
2875//    mymaps.put(a, url);
2876//  }
2877//    Map<ConceptMap, String> mymaps = new HashMap<ConceptMap, String>();
2878//  for (ConceptMap a : context.findMapsForSource(cs.getValueSet())) {
2879//    String url = "";
2880//    ValueSet vsr = context.fetchResource(ValueSet.class, ((Reference) a.getTarget()).getReference());
2881//    if (vsr != null)
2882//      url = (String) vsr.getUserData("filename");
2883//    mymaps.put(a, url);
2884//  }
2885    // also, look in the contained resources for a concept map
2886//    for (Resource r : cs.getContained()) {
2887//      if (r instanceof ConceptMap) {
2888//        ConceptMap cm = (ConceptMap) r;
2889//        if (((Reference) cm.getSource()).getReference().equals(cs.getValueSet())) {
2890//          String url = "";
2891//          ValueSet vsr = context.fetchResource(ValueSet.class, ((Reference) cm.getTarget()).getReference());
2892//          if (vsr != null)
2893//              url = (String) vsr.getUserData("filename");
2894//        mymaps.put(cm, url);
2895//        }
2896//      }
2897//    }
2898  }
2899
2900  private ConceptMapRenderInstructions findByTarget(Type source) {
2901    String src = source.primitiveValue();
2902    if (src != null)
2903      for (ConceptMapRenderInstructions t : renderingMaps) {
2904        if (src.equals(t.url))
2905          return t;
2906      }
2907    return null;
2908  }
2909
2910  private boolean isSource(ValueSet vs, Type source) {
2911    return vs.hasUrl() && source != null && vs.getUrl().equals(source.primitiveValue());
2912  }
2913
2914  private Integer countMembership(ValueSet vs) {
2915    int count = 0;
2916    if (vs.hasExpansion())
2917      count = count + conceptCount(vs.getExpansion().getContains());
2918    else {
2919      if (vs.hasCompose()) {
2920        if (vs.getCompose().hasExclude()) {
2921          try {
2922            ValueSetExpansionOutcome vse = context.expandVS(vs, true, false);
2923            count = 0;
2924            count += conceptCount(vse.getValueset().getExpansion().getContains());
2925            return count;
2926          } catch (Exception e) {
2927            return null;
2928          }
2929        }
2930        for (ConceptSetComponent inc : vs.getCompose().getInclude()) {
2931          if (inc.hasFilter())
2932            return null;
2933          if (!inc.hasConcept())
2934            return null;
2935          count = count + inc.getConcept().size();
2936        }
2937      }
2938    }
2939    return count;
2940  }
2941
2942  private int conceptCount(List<ValueSetExpansionContainsComponent> list) {
2943    int count = 0;
2944    for (ValueSetExpansionContainsComponent c : list) {
2945      if (!c.getAbstract())
2946        count++;
2947      count = count + conceptCount(c.getContains());
2948    }
2949    return count;
2950  }
2951
2952  private boolean generateExpansion(XhtmlNode x, ValueSet vs, ValueSet src, boolean header, List<UsedConceptMap> maps) throws FHIRFormatError, DefinitionException, IOException {
2953    boolean hasExtensions = false;
2954    List<String> langs = new ArrayList<String>();
2955
2956
2957    if (header) {
2958      XhtmlNode h = x.addTag(getHeader());
2959      h.tx("Value Set Contents");
2960      if (IsNotFixedExpansion(vs))
2961        addMarkdown(x, vs.getDescription());
2962      if (vs.hasCopyright())
2963        generateCopyright(x, vs);
2964    }
2965    if (ToolingExtensions.hasExtension(vs.getExpansion(), "http://hl7.org/fhir/StructureDefinition/valueset-toocostly"))
2966      x.para().setAttribute("style", "border: maroon 1px solid; background-color: #FFCCCC; font-weight: bold; padding: 8px").addText(vs.getExpansion().getContains().isEmpty() ? tooCostlyNoteEmpty : tooCostlyNoteNotEmpty );
2967    else {
2968      Integer count = countMembership(vs);
2969      if (count == null)
2970        x.para().tx("This value set does not contain a fixed number of concepts");
2971      else
2972        x.para().tx("This value set contains "+count.toString()+" concepts");
2973    }
2974
2975    generateVersionNotice(x, vs.getExpansion());
2976
2977    CodeSystem allCS = null;
2978    boolean doLevel = false;
2979    for (ValueSetExpansionContainsComponent cc : vs.getExpansion().getContains()) {
2980      if (cc.hasContains()) {
2981        doLevel = true;
2982        break;
2983      }
2984    }
2985    
2986    boolean doSystem = true; // checkDoSystem(vs, src);
2987    boolean doDefinition = checkDoDefinition(vs.getExpansion().getContains());
2988    if (doSystem && allFromOneSystem(vs)) {
2989      doSystem = false;
2990      XhtmlNode p = x.para();
2991      p.tx("All codes from system ");
2992      allCS = context.fetchCodeSystem(vs.getExpansion().getContains().get(0).getSystem());
2993      String ref = null;
2994      if (allCS != null)
2995        ref = getCsRef(allCS);
2996      if (ref == null)
2997        p.code(vs.getExpansion().getContains().get(0).getSystem());
2998      else
2999        p.ah(prefix+ref).code(vs.getExpansion().getContains().get(0).getSystem());
3000    }
3001    XhtmlNode t = x.table( "codes");
3002    XhtmlNode tr = t.tr();
3003    if (doLevel)
3004      tr.td().b().tx("Lvl");
3005    tr.td().attribute("style", "white-space:nowrap").b().tx("Code");
3006    if (doSystem)
3007      tr.td().b().tx("System");
3008    tr.td().b().tx("Display");
3009    if (doDefinition)
3010      tr.td().b().tx("Definition");
3011
3012    addMapHeaders(tr, maps);
3013    for (ValueSetExpansionContainsComponent c : vs.getExpansion().getContains()) {
3014      addExpansionRowToTable(t, c, 0, doLevel, doSystem, doDefinition, maps, allCS, langs);
3015    }
3016
3017    // now, build observed languages
3018
3019    if (langs.size() > 0) {
3020      Collections.sort(langs);
3021      x.para().b().tx("Additional Language Displays");
3022      t = x.table( "codes");
3023      tr = t.tr();
3024      tr.td().b().tx("Code");
3025      for (String lang : langs)
3026        tr.td().b().addText(describeLang(lang));
3027      for (ValueSetExpansionContainsComponent c : vs.getExpansion().getContains()) {
3028        addLanguageRow(c, t, langs);
3029      }
3030    }
3031
3032    return hasExtensions;
3033  }
3034
3035  @SuppressWarnings("rawtypes")
3036  private void generateVersionNotice(XhtmlNode x, ValueSetExpansionComponent expansion) {
3037    Map<String, String> versions = new HashMap<String, String>();
3038    for (ValueSetExpansionParameterComponent p : expansion.getParameter()) {
3039      if (p.getName().equals("version")) {
3040        String[] parts = ((PrimitiveType) p.getValue()).asStringValue().split("\\|");
3041        if (parts.length == 2)
3042          versions.put(parts[0], parts[1]);
3043      }
3044    }
3045    if (!versions.isEmpty()) {
3046      StringBuilder b = new StringBuilder();
3047      b.append("Expansion based on ");
3048      boolean first = true;
3049      for (String s : versions.keySet()) {
3050        if (first)
3051          first = false;
3052        else
3053          b.append(", ");
3054        if (!s.equals("http://snomed.info/sct"))
3055          b.append(describeSystem(s)+" version "+versions.get(s));
3056        else {
3057          String[] parts = versions.get(s).split("\\/");
3058          if (parts.length >= 5) {
3059            String m = describeModule(parts[4]);
3060            if (parts.length == 7)
3061              b.append("SNOMED CT "+m+" edition "+formatSCTDate(parts[6]));
3062            else
3063              b.append("SNOMED CT "+m+" edition");
3064          } else
3065            b.append(describeSystem(s)+" version "+versions.get(s));
3066        }
3067      }
3068
3069      x.para().setAttribute("style", "border: black 1px dotted; background-color: #EEEEEE; padding: 8px").addText(b.toString());
3070    }
3071  }
3072
3073  private String formatSCTDate(String ds) {
3074    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
3075    Date date;
3076    try {
3077      date = format.parse(ds);
3078    } catch (ParseException e) {
3079      return ds;
3080    }
3081    return new SimpleDateFormat("dd-MMM yyyy").format(date);
3082  }
3083
3084  private String describeModule(String module) {
3085    if ("900000000000207008".equals(module))
3086      return "International";
3087    if ("731000124108".equals(module))
3088      return "United States";
3089    if ("32506021000036107".equals(module))
3090      return "Australian";
3091    if ("449081005".equals(module))
3092      return "Spanish";
3093    if ("554471000005108".equals(module))
3094      return "Danish";
3095    if ("11000146104".equals(module))
3096      return "Dutch";
3097    if ("45991000052106".equals(module))
3098      return "Swedish";
3099    if ("999000041000000102".equals(module))
3100      return "United Kingdon";
3101    return module;
3102  }
3103
3104  private boolean hasVersionParameter(ValueSetExpansionComponent expansion) {
3105    for (ValueSetExpansionParameterComponent p : expansion.getParameter()) {
3106      if (p.getName().equals("version"))
3107        return true;
3108    }
3109    return false;
3110  }
3111
3112  private void addLanguageRow(ValueSetExpansionContainsComponent c, XhtmlNode t, List<String> langs) {
3113    XhtmlNode tr = t.tr();
3114    tr.td().addText(c.getCode());
3115    for (String lang : langs) {
3116      String d = null;
3117      for (Extension ext : c.getExtension()) {
3118        if (ToolingExtensions.EXT_TRANSLATION.equals(ext.getUrl())) {
3119          String l = ToolingExtensions.readStringExtension(ext, "lang");
3120          if (lang.equals(l))
3121            d = ToolingExtensions.readStringExtension(ext, "content");
3122        }
3123      }
3124      tr.td().addText(d == null ? "" : d);
3125    }
3126    for (ValueSetExpansionContainsComponent cc : c.getContains()) {
3127      addLanguageRow(cc, t, langs);
3128    }
3129  }
3130
3131
3132  private String describeLang(String lang) {
3133    ValueSet v = context.fetchResource(ValueSet.class, "http://hl7.org/fhir/ValueSet/languages");
3134    if (v != null) {
3135      ConceptReferenceComponent l = null;
3136      for (ConceptReferenceComponent cc : v.getCompose().getIncludeFirstRep().getConcept()) {
3137        if (cc.getCode().equals(lang))
3138          l = cc;
3139      }
3140      if (l == null) {
3141        if (lang.contains("-"))
3142          lang = lang.substring(0, lang.indexOf("-"));
3143        for (ConceptReferenceComponent cc : v.getCompose().getIncludeFirstRep().getConcept()) {
3144          if (cc.getCode().equals(lang) || cc.getCode().startsWith(lang+"-"))
3145            l = cc;
3146        }
3147      }
3148      if (l != null) {
3149        if (lang.contains("-"))
3150          lang = lang.substring(0, lang.indexOf("-"));
3151        String en = l.getDisplay();
3152        String nativelang = null;
3153        for (ConceptReferenceDesignationComponent cd : l.getDesignation()) {
3154          if (cd.getLanguage().equals(lang))
3155            nativelang = cd.getValue();
3156        }
3157        if (nativelang == null)
3158          return en+" ("+lang+")";
3159        else
3160          return nativelang+" ("+en+", "+lang+")";
3161      }
3162    }
3163    return lang;
3164  }
3165
3166
3167  private boolean checkDoDefinition(List<ValueSetExpansionContainsComponent> contains) {
3168    for (ValueSetExpansionContainsComponent c : contains) {
3169      CodeSystem cs = context.fetchCodeSystem(c.getSystem());
3170      if (cs != null)
3171        return true;
3172      if (checkDoDefinition(c.getContains()))
3173        return true;
3174    }
3175    return false;
3176  }
3177
3178
3179  private boolean allFromOneSystem(ValueSet vs) {
3180    if (vs.getExpansion().getContains().isEmpty())
3181      return false;
3182    String system = vs.getExpansion().getContains().get(0).getSystem();
3183    for (ValueSetExpansionContainsComponent cc : vs.getExpansion().getContains()) {
3184      if (!checkSystemMatches(system, cc))
3185        return false;
3186    }
3187    return true;
3188  }
3189
3190
3191  private boolean checkSystemMatches(String system, ValueSetExpansionContainsComponent cc) {
3192    if (!system.equals(cc.getSystem()))
3193      return false;
3194    for (ValueSetExpansionContainsComponent cc1 : cc.getContains()) {
3195      if (!checkSystemMatches(system, cc1))
3196        return false;
3197    }
3198     return true;
3199  }
3200
3201
3202  private boolean checkDoSystem(ValueSet vs, ValueSet src) {
3203    if (src != null)
3204      vs = src;
3205    return vs.hasCompose();
3206  }
3207
3208  private boolean IsNotFixedExpansion(ValueSet vs) {
3209    if (vs.hasCompose())
3210      return false;
3211
3212
3213    // it's not fixed if it has any includes that are not version fixed
3214    for (ConceptSetComponent cc : vs.getCompose().getInclude()) {
3215      if (cc.hasValueSet())
3216        return true;
3217      if (!cc.hasVersion())
3218        return true;
3219    }
3220    return false;
3221  }
3222
3223
3224  private void addLanguageRow(ConceptDefinitionComponent c, XhtmlNode t, List<String> langs) {
3225    XhtmlNode tr = t.tr();
3226    tr.td().addText(c.getCode());
3227    for (String lang : langs) {
3228      ConceptDefinitionDesignationComponent d = null;
3229      for (ConceptDefinitionDesignationComponent designation : c.getDesignation()) {
3230        if (designation.hasLanguage()) {
3231          if (lang.equals(designation.getLanguage()))
3232            d = designation;
3233        }
3234      }
3235      tr.td().addText(d == null ? "" : d.getValue());
3236    }
3237  }
3238
3239//  private void scanLangs(ConceptDefinitionComponent c, List<String> langs) {
3240//    for (ConceptDefinitionDesignationComponent designation : c.getDesignation()) {
3241//      if (designation.hasLanguage()) {
3242//        String lang = designation.getLanguage();
3243//        if (langs != null && !langs.contains(lang) && c.hasDisplay() && !c.getDisplay().equalsIgnoreCase(designation.getValue()))
3244//          langs.add(lang);
3245//      }
3246//    }
3247//    for (ConceptDefinitionComponent g : c.getConcept())
3248//      scanLangs(g, langs);
3249//  }
3250
3251  private void addMapHeaders(XhtmlNode tr, List<UsedConceptMap> maps) throws FHIRFormatError, DefinitionException, IOException {
3252          for (UsedConceptMap m : maps) {
3253                XhtmlNode td = tr.td();
3254                XhtmlNode b = td.b();
3255                XhtmlNode a = b.ah(prefix+m.getLink());
3256      a.addText(m.getDetails().getName());
3257      if (m.getDetails().isDoDescription() && m.getMap().hasDescription())
3258        addMarkdown(td, m.getMap().getDescription());
3259          }
3260  }
3261
3262        private void smartAddText(XhtmlNode p, String text) {
3263          if (text == null)
3264            return;
3265
3266    String[] lines = text.split("\\r\\n");
3267    for (int i = 0; i < lines.length; i++) {
3268      if (i > 0)
3269        p.br();
3270      p.addText(lines[i]);
3271    }
3272  }
3273
3274  private boolean conceptsHaveComments(ConceptDefinitionComponent c) {
3275    if (ToolingExtensions.hasCSComment(c))
3276      return true;
3277    for (ConceptDefinitionComponent g : c.getConcept())
3278      if (conceptsHaveComments(g))
3279        return true;
3280    return false;
3281  }
3282
3283  private boolean conceptsHaveDisplay(ConceptDefinitionComponent c) {
3284    if (c.hasDisplay())
3285      return true;
3286    for (ConceptDefinitionComponent g : c.getConcept())
3287      if (conceptsHaveDisplay(g))
3288        return true;
3289    return false;
3290  }
3291
3292  private boolean conceptsHaveVersion(ConceptDefinitionComponent c) {
3293    if (c.hasUserData("cs.version.notes"))
3294      return true;
3295    for (ConceptDefinitionComponent g : c.getConcept())
3296      if (conceptsHaveVersion(g))
3297        return true;
3298    return false;
3299  }
3300
3301  private boolean conceptsHaveDeprecated(CodeSystem cs, ConceptDefinitionComponent c) {
3302    if (CodeSystemUtilities.isDeprecated(cs, c))
3303      return true;
3304    for (ConceptDefinitionComponent g : c.getConcept())
3305      if (conceptsHaveDeprecated(cs, g))
3306        return true;
3307    return false;
3308  }
3309
3310  private void generateCopyright(XhtmlNode x, ValueSet vs) {
3311    XhtmlNode p = x.para();
3312    p.b().tx("Copyright Statement:");
3313    smartAddText(p, " " + vs.getCopyright());
3314  }
3315
3316  private XhtmlNode addTableHeaderRowStandard(XhtmlNode t, boolean hasHierarchy, boolean hasDisplay, boolean definitions, boolean comments, boolean version, boolean deprecated, String lang, List<PropertyComponent> properties) {
3317    XhtmlNode tr = t.tr();
3318    if (hasHierarchy)
3319      tr.td().b().tx("Lvl");
3320    tr.td().attribute("style", "white-space:nowrap").b().tx(context.translator().translate("xhtml-gen-cs", "Code", lang));
3321    if (hasDisplay)
3322      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Display", lang));
3323    if (definitions)
3324      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Definition", lang));
3325    if (deprecated)
3326      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Deprecated", lang));
3327    if (comments)
3328      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Comments", lang));
3329    if (version)
3330      tr.td().b().tx(context.translator().translate("xhtml-gen-cs", "Version", lang));
3331    if (properties != null) {
3332      for (PropertyComponent pc : properties) {
3333        tr.td().b().tx(context.translator().translate("xhtml-gen-cs", ToolingExtensions.getPresentation(pc, pc.getCodeElement()), lang));      
3334      }
3335    }
3336    return tr;
3337  }
3338
3339  private void addExpansionRowToTable(XhtmlNode t, ValueSetExpansionContainsComponent c, int i, boolean doLevel, boolean doSystem, boolean doDefinition, List<UsedConceptMap> maps, CodeSystem allCS, List<String> langs) {
3340    XhtmlNode tr = t.tr();
3341    XhtmlNode td = tr.td();
3342
3343    String tgt = makeAnchor(c.getSystem(), c.getCode());
3344    td.an(tgt);
3345
3346    if (doLevel) {
3347      td.addText(Integer.toString(i));
3348      td = tr.td();
3349    }
3350    String s = Utilities.padLeft("", '\u00A0', i*2);
3351    td.attribute("style", "white-space:nowrap").addText(s);
3352    addCodeToTable(c.getAbstract(), c.getSystem(), c.getCode(), c.getDisplay(), td);
3353    if (doSystem) {
3354      td = tr.td();
3355      td.addText(c.getSystem());
3356    }
3357    td = tr.td();
3358    if (c.hasDisplayElement())
3359      td.addText(c.getDisplay());
3360
3361    if (doDefinition) {
3362      CodeSystem cs = allCS;
3363      if (cs == null)
3364        cs = context.fetchCodeSystem(c.getSystem());
3365      td = tr.td();
3366      if (cs != null)
3367        td.addText(CodeSystemUtilities.getCodeDefinition(cs, c.getCode()));
3368    }
3369    for (UsedConceptMap m : maps) {
3370      td = tr.td();
3371      List<TargetElementComponentWrapper> mappings = findMappingsForCode(c.getCode(), m.getMap());
3372      boolean first = true;
3373      for (TargetElementComponentWrapper mapping : mappings) {
3374        if (!first)
3375            td.br();
3376        first = false;
3377        XhtmlNode span = td.span(null, mapping.comp.getRelationship().toString());
3378        span.addText(getCharForRelationship(mapping.comp));
3379        addRefToCode(td, mapping.group.getTarget(), m.getLink(), mapping.comp.getCode()); 
3380        if (!Utilities.noString(mapping.comp.getComment()))
3381          td.i().tx("("+mapping.comp.getComment()+")");
3382      }
3383    }
3384    for (Extension ext : c.getExtension()) {
3385      if (ToolingExtensions.EXT_TRANSLATION.equals(ext.getUrl())) {
3386        String lang = ToolingExtensions.readStringExtension(ext,  "lang");
3387        if (!Utilities.noString(lang) && !langs.contains(lang))
3388          langs.add(lang);
3389      }
3390    }
3391    for (ValueSetExpansionContainsComponent cc : c.getContains()) {
3392      addExpansionRowToTable(t, cc, i+1, doLevel, doSystem, doDefinition, maps, allCS, langs);
3393    }
3394  }
3395
3396  private void addCodeToTable(boolean isAbstract, String system, String code, String display, XhtmlNode td) {
3397    CodeSystem e = context.fetchCodeSystem(system);
3398    if (e == null || e.getContent() != org.hl7.fhir.r5.model.CodeSystem.CodeSystemContentMode.COMPLETE) {
3399      if (isAbstract)
3400        td.i().setAttribute("title", ABSTRACT_CODE_HINT).addText(code);
3401      else if ("http://snomed.info/sct".equals(system)) {
3402        td.ah(sctLink(code)).addText(code);
3403      } else if ("http://loinc.org".equals(system)) {
3404          td.ah("http://details.loinc.org/LOINC/"+code+".html").addText(code);
3405      } else        
3406        td.addText(code);
3407    } else {
3408      String href = prefix+getCsRef(e);
3409      if (href.contains("#"))
3410        href = href + "-"+Utilities.nmtokenize(code);
3411      else
3412        href = href + "#"+e.getId()+"-"+Utilities.nmtokenize(code);
3413      if (isAbstract)
3414        td.ah(href).setAttribute("title", ABSTRACT_CODE_HINT).i().addText(code);
3415      else
3416        td.ah(href).addText(code);
3417    }
3418  }
3419
3420  public String sctLink(String code) {
3421//    if (snomedEdition != null)
3422//      http://browser.ihtsdotools.org/?perspective=full&conceptId1=428041000124106&edition=us-edition&release=v20180301&server=https://prod-browser-exten.ihtsdotools.org/api/snomed&langRefset=900000000000509007
3423    return "http://browser.ihtsdotools.org/?perspective=full&conceptId1="+code;
3424  }
3425
3426  private class TargetElementComponentWrapper {
3427    private ConceptMapGroupComponent group;
3428    private TargetElementComponent comp;
3429    public TargetElementComponentWrapper(ConceptMapGroupComponent group, TargetElementComponent comp) {
3430      super();
3431      this.group = group;
3432      this.comp = comp;
3433    }
3434
3435  }
3436
3437  private String langDisplay(String l, boolean isShort) {
3438    ValueSet vs = context.fetchResource(ValueSet.class, "http://hl7.org/fhir/ValueSet/languages");
3439    for (ConceptReferenceComponent vc : vs.getCompose().getInclude().get(0).getConcept()) {
3440      if (vc.getCode().equals(l)) {
3441        for (ConceptReferenceDesignationComponent cd : vc.getDesignation()) {
3442          if (cd.getLanguage().equals(l))
3443            return cd.getValue()+(isShort ? "" : " ("+vc.getDisplay()+")");
3444        }
3445        return vc.getDisplay();
3446      }
3447    }
3448    return "??Lang";
3449  }
3450 
3451  private boolean addDefineRowToTable(XhtmlNode t, ConceptDefinitionComponent c, int i, boolean hasHierarchy, boolean hasDisplay, boolean comment, boolean version, boolean deprecated, List<UsedConceptMap> maps, String system, CodeSystem cs, String lang, List<PropertyComponent> properties) throws FHIRFormatError, DefinitionException, IOException {
3452    boolean hasExtensions = false;
3453    XhtmlNode tr = t.tr();
3454    XhtmlNode td = tr.td();
3455    if (hasHierarchy) {
3456      td.addText(Integer.toString(i+1));
3457      td = tr.td();
3458      String s = Utilities.padLeft("", '\u00A0', i*2);
3459      td.addText(s);
3460    }
3461    td.attribute("style", "white-space:nowrap").addText(c.getCode());
3462    XhtmlNode a;
3463    if (c.hasCodeElement()) {
3464      td.an(cs.getId()+"-" + Utilities.nmtokenize(c.getCode()));
3465    }
3466
3467    if (hasDisplay) {
3468      td = tr.td();
3469      if (c.hasDisplayElement()) {
3470        if (lang == null) {
3471          td.addText(c.getDisplay());
3472        } else if (lang.equals("*")) {
3473          boolean sl = false;
3474          for (ConceptDefinitionDesignationComponent cd : c.getDesignation()) 
3475            if (cd.getUse().is("http://terminology.hl7.org/CodeSystem/designation-usage", "display") && cd.hasLanguage() && !c.getDisplay().equalsIgnoreCase(cd.getValue())) 
3476              sl = true;
3477          td.addText((sl ? cs.getLanguage("en")+": " : "")+c.getDisplay());
3478          for (ConceptDefinitionDesignationComponent cd : c.getDesignation()) {
3479            if (cd.getUse().is("http://terminology.hl7.org/CodeSystem/designation-usage", "display") && cd.hasLanguage() && !c.getDisplay().equalsIgnoreCase(cd.getValue())) {
3480              td.br();
3481              td.addText(cd.getLanguage()+": "+cd.getValue());
3482            }
3483          }
3484       } else if (lang.equals(cs.getLanguage()) || (lang.equals("en") && !cs.hasLanguage())) {
3485         td.addText(c.getDisplay());
3486       } else {
3487         for (ConceptDefinitionDesignationComponent cd : c.getDesignation()) {
3488           if (cd.getUse().is("http://terminology.hl7.org/CodeSystem/designation-usage", "display") && cd.hasLanguage() && cd.getLanguage().equals(lang)) {
3489             td.addText(cd.getValue());
3490           }
3491         }
3492       }
3493      }
3494    }
3495    td = tr.td();
3496    if (c != null && 
3497        c.hasDefinitionElement()) {
3498      if (lang == null) {
3499        if (hasMarkdownInDefinitions(cs))
3500          addMarkdown(td, c.getDefinition());
3501        else
3502          td.addText(c.getDefinition());
3503      } else if (lang.equals("*")) {
3504        boolean sl = false;
3505        for (ConceptDefinitionDesignationComponent cd : c.getDesignation()) 
3506          if (cd.getUse().is("http://terminology.hl7.org/CodeSystem/designation-usage", "definition") && cd.hasLanguage() && !c.getDefinition().equalsIgnoreCase(cd.getValue())) 
3507            sl = true;
3508        td.addText((sl ? cs.getLanguage("en")+": " : "")+c.getDefinition());
3509        for (ConceptDefinitionDesignationComponent cd : c.getDesignation()) {
3510          if (cd.getUse().is("http://terminology.hl7.org/CodeSystem/designation-usage", "definition") && cd.hasLanguage() && !c.getDefinition().equalsIgnoreCase(cd.getValue())) {
3511            td.br();
3512            td.addText(cd.getLanguage()+": "+cd.getValue());
3513          }
3514        }
3515     } else if (lang.equals(cs.getLanguage()) || (lang.equals("en") && !cs.hasLanguage())) {
3516       td.addText(c.getDefinition());
3517     } else {
3518       for (ConceptDefinitionDesignationComponent cd : c.getDesignation()) {
3519         if (cd.getUse().is("http://terminology.hl7.org/CodeSystem/designation-usage", "definition") && cd.hasLanguage() && cd.getLanguage().equals(lang)) {
3520           td.addText(cd.getValue());
3521         }
3522       }
3523     }
3524    }
3525    if (deprecated) {
3526      td = tr.td();
3527      Boolean b = CodeSystemUtilities.isDeprecated(cs, c);
3528      if (b !=  null && b) {
3529        smartAddText(td, context.translator().translate("xhtml-gen-cs", "Deprecated", lang));
3530        hasExtensions = true;
3531        if (ToolingExtensions.hasExtension(c, ToolingExtensions.EXT_REPLACED_BY)) {
3532          Coding cc = (Coding) ToolingExtensions.getExtension(c, ToolingExtensions.EXT_REPLACED_BY).getValue();
3533          td.tx(" (replaced by ");
3534          String url = getCodingReference(cc, system);
3535          if (url != null) {
3536            td.ah(url).addText(cc.getCode());
3537            td.tx(": "+cc.getDisplay()+")");
3538          } else
3539            td.addText(cc.getCode()+" '"+cc.getDisplay()+"' in "+cc.getSystem()+")");
3540        }
3541      }
3542    }
3543    if (comment) {
3544      td = tr.td();
3545      Extension ext = c.getExtensionByUrl(ToolingExtensions.EXT_CS_COMMENT);
3546      if (ext != null) {
3547        hasExtensions = true;
3548        String bc = ext.hasValue() ? ext.getValue().primitiveValue() : null;
3549        Map<String, String> translations = ToolingExtensions.getLanguageTranslations(ext.getValue());
3550
3551        if (lang == null) {
3552          if (bc != null)
3553            td.addText(bc);
3554        } else if (lang.equals("*")) {
3555          boolean sl = false;
3556          for (String l : translations.keySet()) 
3557            if (bc == null || !bc.equalsIgnoreCase(translations.get(l))) 
3558              sl = true;
3559          if (bc != null) {
3560            td.addText((sl ? cs.getLanguage("en")+": " : "")+bc);
3561          }
3562          for (String l : translations.keySet()) {
3563            if (bc == null || !bc.equalsIgnoreCase(translations.get(l))) {
3564              if (!td.getChildNodes().isEmpty()) 
3565                td.br();
3566              td.addText(l+": "+translations.get(l));
3567            }
3568          }
3569        } else if (lang.equals(cs.getLanguage()) || (lang.equals("en") && !cs.hasLanguage())) {
3570          if (bc != null)
3571            td.addText(bc);
3572        } else {
3573          if (bc != null)
3574            translations.put(cs.getLanguage("en"), bc);
3575          for (String l : translations.keySet()) { 
3576            if (l.equals(lang)) {
3577              td.addText(translations.get(l));
3578            }
3579          }
3580        }
3581      }      
3582    }
3583    if (version) {
3584      td = tr.td();
3585      if (c.hasUserData("cs.version.notes"))
3586        td.addText(c.getUserString("cs.version.notes"));
3587    }
3588    if (properties != null) {
3589      for (PropertyComponent pc : properties) {
3590        td = tr.td();
3591        boolean first = true;
3592        ConceptPropertyComponent pcv = CodeSystemUtilities.getProperty(c, pc.getCode());
3593        if (pcv != null && pcv.hasValue()) {
3594          if (first) first = false; else td.addText(", ");
3595          if (pcv.hasValueCoding()) { 
3596            td.addText(pcv.getValueCoding().getCode());
3597          } else {
3598            td.addText(pcv.getValue().primitiveValue());
3599          }
3600        }
3601      }
3602    }
3603    
3604    for (UsedConceptMap m : maps) {
3605      td = tr.td();
3606      List<TargetElementComponentWrapper> mappings = findMappingsForCode(c.getCode(), m.getMap());
3607      boolean first = true;
3608      for (TargetElementComponentWrapper mapping : mappings) {
3609        if (!first)
3610                  td.br();
3611        first = false;
3612        XhtmlNode span = td.span(null, mapping.comp.hasRelationship() ?  mapping.comp.getRelationship().toCode() : "");
3613        span.addText(getCharForRelationship(mapping.comp));
3614        a = td.ah(prefix+m.getLink()+"#"+makeAnchor(mapping.group.getTarget(), mapping.comp.getCode()));
3615        a.addText(mapping.comp.getCode());
3616        if (!Utilities.noString(mapping.comp.getComment()))
3617          td.i().tx("("+mapping.comp.getComment()+")");
3618      }
3619    }
3620    for (String e : CodeSystemUtilities.getOtherChildren(cs, c)) {
3621      tr = t.tr();
3622      td = tr.td();
3623      String s = Utilities.padLeft("", '.', i*2);
3624      td.addText(s);
3625      a = td.ah("#"+Utilities.nmtokenize(e));
3626      a.addText(c.getCode());
3627    }
3628    for (ConceptDefinitionComponent cc : c.getConcept()) {
3629      hasExtensions = addDefineRowToTable(t, cc, i+1, hasHierarchy, hasDisplay, comment, version, deprecated, maps, system, cs, lang, properties) || hasExtensions;
3630    }
3631    return hasExtensions;
3632  }
3633
3634
3635  private boolean hasMarkdownInDefinitions(CodeSystem cs) {
3636    return ToolingExtensions.readBoolExtension(cs, "http://hl7.org/fhir/StructureDefinition/codesystem-use-markdown");
3637  }
3638
3639  private String makeAnchor(String codeSystem, String code) {
3640    String s = codeSystem+'-'+code;
3641    StringBuilder b = new StringBuilder();
3642    for (char c : s.toCharArray()) {
3643      if (Character.isAlphabetic(c) || Character.isDigit(c) || c == '.')
3644        b.append(c);
3645      else
3646        b.append('-');
3647    }
3648    return b.toString();
3649  }
3650
3651  private String getCodingReference(Coding cc, String system) {
3652    if (cc.getSystem().equals(system))
3653      return "#"+cc.getCode();
3654    if (cc.getSystem().equals("http://snomed.info/sct"))
3655      return "http://snomed.info/sct/"+cc.getCode();
3656    if (cc.getSystem().equals("http://loinc.org"))
3657      return "http://s.details.loinc.org/LOINC/"+cc.getCode()+".html";
3658    return null;
3659  }
3660
3661  private String getCharForRelationship(TargetElementComponent mapping) {
3662    if (!mapping.hasRelationship())
3663      return "";
3664          switch (mapping.getRelationship()) {
3665          case EQUIVALENT : return "~";
3666          case BROADER : return "<";
3667          case NARROWER : return ">";
3668          case NOTRELATEDTO : return "!=";
3669    default: return "?";
3670          }
3671  }
3672
3673  private List<TargetElementComponentWrapper> findMappingsForCode(String code, ConceptMap map) {
3674    List<TargetElementComponentWrapper> mappings = new ArrayList<TargetElementComponentWrapper>();
3675
3676    for (ConceptMapGroupComponent g : map.getGroup()) {
3677      for (SourceElementComponent c : g.getElement()) {
3678                if (c.getCode().equals(code))
3679          for (TargetElementComponent cc : c.getTarget())
3680            mappings.add(new TargetElementComponentWrapper(g, cc));
3681      }
3682          }
3683          return mappings;
3684  }
3685
3686  private boolean generateComposition(ResourceContext rcontext, XhtmlNode x, ValueSet vs, boolean header, List<UsedConceptMap> maps) throws FHIRException, IOException {
3687          boolean hasExtensions = false;
3688    List<String> langs = new ArrayList<String>();
3689
3690    if (header) {
3691      XhtmlNode h = x.h2();
3692      h.addText(vs.present());
3693      addMarkdown(x, vs.getDescription());
3694      if (vs.hasCopyrightElement())
3695        generateCopyright(x, vs);
3696    }
3697    XhtmlNode p = x.para();
3698    p.tx("This value set includes codes from the following code systems:");
3699
3700    XhtmlNode ul = x.ul();
3701    XhtmlNode li;
3702    for (ConceptSetComponent inc : vs.getCompose().getInclude()) {
3703      hasExtensions = genInclude(rcontext, ul, inc, "Include", langs, maps) || hasExtensions;
3704    }
3705    for (ConceptSetComponent exc : vs.getCompose().getExclude()) {
3706      hasExtensions = genInclude(rcontext, ul, exc, "Exclude", langs, maps) || hasExtensions;
3707    }
3708
3709    // now, build observed languages
3710
3711    if (langs.size() > 0) {
3712      Collections.sort(langs);
3713      x.para().b().tx("Additional Language Displays");
3714      XhtmlNode t = x.table( "codes");
3715      XhtmlNode tr = t.tr();
3716      tr.td().b().tx("Code");
3717      for (String lang : langs)
3718        tr.td().b().addText(describeLang(lang));
3719      for (ConceptSetComponent c : vs.getCompose().getInclude()) {
3720        for (ConceptReferenceComponent cc : c.getConcept()) {
3721          addLanguageRow(cc, t, langs);
3722        }
3723      }
3724    }
3725
3726    return hasExtensions;
3727  }
3728
3729    private void addLanguageRow(ConceptReferenceComponent c, XhtmlNode t, List<String> langs) {
3730      XhtmlNode tr = t.tr();
3731      tr.td().addText(c.getCode());
3732      for (String lang : langs) {
3733        String d = null;
3734        for (ConceptReferenceDesignationComponent cd : c.getDesignation()) {
3735          String l = cd.getLanguage();
3736          if (lang.equals(l))
3737            d = cd.getValue();
3738        }
3739        tr.td().addText(d == null ? "" : d);
3740      }
3741    }
3742
3743  private void AddVsRef(ResourceContext rcontext, String value, XhtmlNode li) {
3744    Resource res = rcontext == null ? null : rcontext.resolve(value); 
3745    if (res != null && !(res instanceof MetadataResource)) {
3746      li.addText(value);
3747      return;      
3748    }      
3749    MetadataResource vs = (MetadataResource) res;
3750    if (vs == null)
3751                vs = context.fetchResource(ValueSet.class, value);
3752    if (vs == null)
3753                vs = context.fetchResource(StructureDefinition.class, value);
3754//    if (vs == null)
3755        //      vs = context.fetchResource(DataElement.class, value);
3756    if (vs == null)
3757                vs = context.fetchResource(Questionnaire.class, value);
3758    if (vs != null) {
3759      String ref = (String) vs.getUserData("path");
3760      
3761      ref = adjustForPath(ref);
3762      XhtmlNode a = li.ah(ref == null ? "??" : ref.replace("\\", "/"));
3763      a.addText(value);
3764    } else {
3765        CodeSystem cs = context.fetchCodeSystem(value);
3766        if (cs != null) {
3767        String ref = (String) cs.getUserData("path");
3768        ref = adjustForPath(ref);
3769        XhtmlNode a = li.ah(ref == null ? "??" : ref.replace("\\", "/"));
3770        a.addText(value);
3771            } else if (value.equals("http://snomed.info/sct") || value.equals("http://snomed.info/id")) {
3772              XhtmlNode a = li.ah(value);
3773              a.tx("SNOMED-CT");
3774            }
3775            else {
3776              if (value.startsWith("http://hl7.org") && !Utilities.existsInList(value, "http://hl7.org/fhir/sid/icd-10-us"))
3777                System.out.println("Unable to resolve value set "+value);
3778              li.addText(value);
3779    }
3780  }
3781        }
3782
3783  private String adjustForPath(String ref) {
3784    if (prefix == null)
3785      return ref;
3786    else
3787      return prefix+ref;
3788  }
3789
3790  private boolean genInclude(ResourceContext rcontext, XhtmlNode ul, ConceptSetComponent inc, String type, List<String> langs, List<UsedConceptMap> maps) throws FHIRException, IOException {
3791    boolean hasExtensions = false;
3792    XhtmlNode li;
3793    li = ul.li();
3794    CodeSystem e = context.fetchCodeSystem(inc.getSystem());
3795
3796    if (inc.hasSystem()) {
3797      if (inc.getConcept().size() == 0 && inc.getFilter().size() == 0) {
3798        li.addText(type+" all codes defined in ");
3799        addCsRef(inc, li, e);
3800      } else {
3801        if (inc.getConcept().size() > 0) {
3802          li.addText(type+" these codes as defined in ");
3803          addCsRef(inc, li, e);
3804
3805          XhtmlNode t = li.table("none");
3806          boolean hasComments = false;
3807          boolean hasDefinition = false;
3808          for (ConceptReferenceComponent c : inc.getConcept()) {
3809            hasComments = hasComments || ExtensionHelper.hasExtension(c, ToolingExtensions.EXT_VS_COMMENT);
3810            hasDefinition = hasDefinition || ExtensionHelper.hasExtension(c, ToolingExtensions.EXT_DEFINITION);
3811          }
3812          if (hasComments || hasDefinition)
3813            hasExtensions = true;
3814          addMapHeaders(addTableHeaderRowStandard(t, false, true, hasDefinition, hasComments, false, false, null, null), maps);
3815          for (ConceptReferenceComponent c : inc.getConcept()) {
3816            XhtmlNode tr = t.tr();
3817            XhtmlNode td = tr.td();
3818            ConceptDefinitionComponent cc = getConceptForCode(e, c.getCode(), inc);
3819            addCodeToTable(false, inc.getSystem(), c.getCode(), c.hasDisplay()? c.getDisplay() : cc != null ? cc.getDisplay() : "", td);
3820
3821            td = tr.td();
3822            if (!Utilities.noString(c.getDisplay()))
3823              td.addText(c.getDisplay());
3824            else if (cc != null && !Utilities.noString(cc.getDisplay()))
3825              td.addText(cc.getDisplay());
3826
3827            td = tr.td();
3828            if (ExtensionHelper.hasExtension(c, ToolingExtensions.EXT_DEFINITION))
3829              smartAddText(td, ToolingExtensions.readStringExtension(c, ToolingExtensions.EXT_DEFINITION));
3830            else if (cc != null && !Utilities.noString(cc.getDefinition()))
3831              smartAddText(td, cc.getDefinition());
3832
3833            if (ExtensionHelper.hasExtension(c, ToolingExtensions.EXT_VS_COMMENT)) {
3834              smartAddText(tr.td(), "Note: "+ToolingExtensions.readStringExtension(c, ToolingExtensions.EXT_VS_COMMENT));
3835            }
3836            for (ConceptReferenceDesignationComponent cd : c.getDesignation()) {
3837              if (cd.hasLanguage() && !langs.contains(cd.getLanguage()))
3838                langs.add(cd.getLanguage());
3839            }
3840          }
3841        }
3842        if (inc.getFilter().size() > 0) {
3843          li.addText(type+" codes from ");
3844          addCsRef(inc, li, e);
3845          li.tx(" where ");
3846          for (int i = 0; i < inc.getFilter().size(); i++) {
3847            ConceptSetFilterComponent f = inc.getFilter().get(i);
3848            if (i > 0) {
3849              if (i == inc.getFilter().size()-1) {
3850                li.tx(" and ");
3851              } else {
3852                li.tx(", ");
3853              }
3854            }
3855            if (f.getOp() == FilterOperator.EXISTS) {
3856              if (f.getValue().equals("true")) {
3857                li.tx(f.getProperty()+" exists");
3858              } else {
3859                li.tx(f.getProperty()+" doesn't exist");
3860              }
3861            } else {
3862              li.tx(f.getProperty()+" "+describe(f.getOp())+" ");
3863              if (e != null && codeExistsInValueSet(e, f.getValue())) {
3864                String href = prefix+getCsRef(e);
3865                if (href.contains("#"))
3866                  href = href + "-"+Utilities.nmtokenize(f.getValue());
3867                else
3868                  href = href + "#"+e.getId()+"-"+Utilities.nmtokenize(f.getValue());
3869                li.ah(href).addText(f.getValue());
3870              } else if ("concept".equals(f.getProperty()) && inc.hasSystem()) {
3871                li.addText(f.getValue());
3872                ValidationResult vr = context.validateCode(terminologyServiceOptions, inc.getSystem(), f.getValue(), null);
3873                if (vr.isOk()) {
3874                  li.tx(" ("+vr.getDisplay()+")");
3875                }
3876              }
3877              else
3878                li.addText(f.getValue());
3879              String disp = ToolingExtensions.getDisplayHint(f);
3880              if (disp != null)
3881                li.tx(" ("+disp+")");
3882            }
3883          }
3884        }
3885      }
3886      if (inc.hasValueSet()) {
3887        li.tx(", where the codes are contained in ");
3888        boolean first = true;
3889        for (UriType vs : inc.getValueSet()) {
3890          if (first)
3891            first = false;
3892          else
3893            li.tx(", ");
3894          AddVsRef(rcontext, vs.asStringValue(), li);
3895        }
3896      }
3897    } else {
3898      li.tx("Import all the codes that are contained in ");
3899      boolean first = true;
3900      for (UriType vs : inc.getValueSet()) {
3901        if (first)
3902          first = false;
3903        else
3904          li.tx(", ");
3905        AddVsRef(rcontext, vs.asStringValue(), li);
3906      }
3907    }
3908    return hasExtensions;
3909  }
3910
3911  private String describe(FilterOperator op) {
3912    if (op == null)
3913      return " null ";
3914    switch (op) {
3915    case EQUAL: return " = ";
3916    case ISA: return " is-a ";
3917    case ISNOTA: return " is-not-a ";
3918    case REGEX: return " matches (by regex) ";
3919                case NULL: return " ?? ";
3920                case IN: return " in ";
3921                case NOTIN: return " not in ";
3922    case DESCENDENTOF: return " descends from ";
3923    case EXISTS: return " exists ";
3924    case GENERALIZES: return " generalizes ";
3925    }
3926    return null;
3927  }
3928
3929  private ConceptDefinitionComponent getConceptForCode(CodeSystem e, String code, ConceptSetComponent inc) {
3930    // first, look in the code systems
3931    if (e == null)
3932    e = context.fetchCodeSystem(inc.getSystem());
3933    if (e != null) {
3934      ConceptDefinitionComponent v = getConceptForCode(e.getConcept(), code);
3935      if (v != null)
3936        return v;
3937    }
3938
3939    if (noSlowLookup)
3940      return null;
3941    
3942    if (!context.hasCache()) {
3943      ValueSetExpansionComponent vse;
3944      try {
3945        ValueSetExpansionOutcome vso = context.expandVS(inc, false);   
3946        ValueSet valueset = vso.getValueset();
3947        if (valueset == null)
3948          throw new TerminologyServiceException("Error Expanding ValueSet: "+vso.getError());
3949        vse = valueset.getExpansion();        
3950
3951      } catch (TerminologyServiceException e1) {
3952        return null;
3953      }
3954      if (vse != null) {
3955        ConceptDefinitionComponent v = getConceptForCodeFromExpansion(vse.getContains(), code);
3956      if (v != null)
3957        return v;
3958    }
3959    }
3960
3961    return context.validateCode(terminologyServiceOptions, inc.getSystem(), code, null).asConceptDefinition();
3962  }
3963
3964
3965
3966  private ConceptDefinitionComponent getConceptForCode(List<ConceptDefinitionComponent> list, String code) {
3967    for (ConceptDefinitionComponent c : list) {
3968    if (code.equals(c.getCode()))
3969      return c;
3970      ConceptDefinitionComponent v = getConceptForCode(c.getConcept(), code);
3971      if (v != null)
3972        return v;
3973    }
3974    return null;
3975  }
3976
3977  private ConceptDefinitionComponent getConceptForCodeFromExpansion(List<ValueSetExpansionContainsComponent> list, String code) {
3978    for (ValueSetExpansionContainsComponent c : list) {
3979      if (code.equals(c.getCode())) {
3980        ConceptDefinitionComponent res = new ConceptDefinitionComponent();
3981        res.setCode(c.getCode());
3982        res.setDisplay(c.getDisplay());
3983        return res;
3984      }
3985      ConceptDefinitionComponent v = getConceptForCodeFromExpansion(c.getContains(), code);
3986      if (v != null)
3987        return v;
3988    }
3989    return null;
3990  }
3991
3992  private void addRefToCode(XhtmlNode td, String target, String vslink, String code) {
3993    CodeSystem cs = context.fetchCodeSystem(target);
3994    String cslink = getCsRef(cs);
3995    XhtmlNode a = null;
3996    if (cslink != null) 
3997      a = td.ah(prefix+cslink+"#"+cs.getId()+"-"+code);
3998    else
3999      a = td.ah(prefix+vslink+"#"+code);
4000    a.addText(code);
4001  }
4002
4003  private  <T extends Resource> void addCsRef(ConceptSetComponent inc, XhtmlNode li, T cs) {
4004    String ref = null;
4005    boolean addHtml = true;
4006    if (cs != null) {
4007      ref = (String) cs.getUserData("external.url");
4008      if (Utilities.noString(ref))
4009        ref = (String) cs.getUserData("filename");
4010      else
4011        addHtml = false;
4012      if (Utilities.noString(ref))
4013        ref = (String) cs.getUserData("path");
4014    }
4015    String spec = getSpecialReference(inc.getSystem());
4016    if (spec != null) {
4017      XhtmlNode a = li.ah(spec);
4018      a.code(inc.getSystem());
4019    } else if (cs != null && ref != null) {
4020      if (!Utilities.noString(prefix) && ref.startsWith("http://hl7.org/fhir/"))
4021        ref = ref.substring(20)+"/index.html";
4022      else if (addHtml && !ref.contains(".html"))
4023        ref = ref + ".html";
4024      XhtmlNode a = li.ah(prefix+ref.replace("\\", "/"));
4025      a.code(inc.getSystem());
4026    } else {
4027      li.code(inc.getSystem());
4028    }
4029  }
4030
4031  private String getSpecialReference(String system) {
4032    if ("http://snomed.info/sct".equals(system))
4033      return "http://www.snomed.org/";
4034    if (Utilities.existsInList(system, "http://loinc.org", "http://unitsofmeasure.org", "http://www.nlm.nih.gov/research/umls/rxnorm", "http://ncimeta.nci.nih.gov", "http://fdasis.nlm.nih.gov", 
4035         "http://www.radlex.org", "http://www.whocc.no/atc", "http://dicom.nema.org/resources/ontology/DCM", "http://www.genenames.org", "http://www.ensembl.org", "http://www.ncbi.nlm.nih.gov/nuccore", 
4036         "http://www.ncbi.nlm.nih.gov/clinvar", "http://sequenceontology.org", "http://www.hgvs.org/mutnomen", "http://www.ncbi.nlm.nih.gov/projects/SNP", "http://cancer.sanger.ac.uk/cancergenome/projects/cosmic", 
4037         "http://www.lrg-sequence.org", "http://www.omim.org", "http://www.ncbi.nlm.nih.gov/pubmed", "http://www.pharmgkb.org", "http://clinicaltrials.gov", "http://www.ebi.ac.uk/ipd/imgt/hla/")) 
4038      return system;
4039      
4040    return null;
4041  }
4042
4043  private String getCsRef(String system) {
4044    CodeSystem cs = context.fetchCodeSystem(system);
4045    return getCsRef(cs);
4046  }
4047
4048  private  <T extends Resource> String getCsRef(T cs) {
4049    String ref = (String) cs.getUserData("filename");
4050    if (ref == null)
4051      ref = (String) cs.getUserData("path");
4052    if (ref == null)
4053      return "??.html";
4054    if (!ref.contains(".html"))
4055      ref = ref + ".html";
4056    return ref.replace("\\", "/");
4057  }
4058
4059  private boolean codeExistsInValueSet(CodeSystem cs, String code) {
4060    for (ConceptDefinitionComponent c : cs.getConcept()) {
4061      if (inConcept(code, c))
4062        return true;
4063    }
4064    return false;
4065  }
4066
4067  private boolean inConcept(String code, ConceptDefinitionComponent c) {
4068    if (c.hasCodeElement() && c.getCode().equals(code))
4069      return true;
4070    for (ConceptDefinitionComponent g : c.getConcept()) {
4071      if (inConcept(code, g))
4072        return true;
4073    }
4074    return false;
4075  }
4076
4077  /**
4078   * This generate is optimised for the build tool in that it tracks the source extension.
4079   * But it can be used for any other use.
4080   *
4081   * @param vs
4082   * @param codeSystems
4083   * @throws DefinitionException
4084   * @throws Exception
4085   */
4086  public boolean generate(ResourceContext rcontext, OperationOutcome op) throws DefinitionException {
4087    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
4088    boolean hasSource = false;
4089    boolean success = true;
4090    for (OperationOutcomeIssueComponent i : op.getIssue()) {
4091        success = success && i.getSeverity() == IssueSeverity.INFORMATION;
4092        hasSource = hasSource || ExtensionHelper.hasExtension(i, ToolingExtensions.EXT_ISSUE_SOURCE);
4093    }
4094    if (success)
4095        x.para().tx("All OK");
4096    if (op.getIssue().size() > 0) {
4097                XhtmlNode tbl = x.table("grid"); // on the basis that we'll most likely be rendered using the standard fhir css, but it doesn't really matter
4098                XhtmlNode tr = tbl.tr();
4099                tr.td().b().tx("Severity");
4100                tr.td().b().tx("Location");
4101        tr.td().b().tx("Code");
4102        tr.td().b().tx("Details");
4103        tr.td().b().tx("Diagnostics");
4104                if (hasSource)
4105                        tr.td().b().tx("Source");
4106                for (OperationOutcomeIssueComponent i : op.getIssue()) {
4107                        tr = tbl.tr();
4108                        tr.td().addText(i.getSeverity().toString());
4109                        XhtmlNode td = tr.td();
4110                        boolean d = false;
4111                        for (StringType s : i.getLocation()) {
4112                                if (d)
4113                                        td.tx(", ");
4114                                else
4115                                        d = true;
4116                                td.addText(s.getValue());
4117                        }
4118          tr.td().addText(i.getCode().getDisplay());
4119          tr.td().addText(gen(i.getDetails()));
4120          smartAddText(tr.td(), i.getDiagnostics());
4121                        if (hasSource) {
4122                                Extension ext = ExtensionHelper.getExtension(i, ToolingExtensions.EXT_ISSUE_SOURCE);
4123            tr.td().addText(ext == null ? "" : gen(ext));
4124                        }
4125                }
4126        }
4127    inject(op, x, hasSource ? NarrativeStatus.EXTENSIONS :  NarrativeStatus.GENERATED);
4128    return true;
4129  }
4130
4131
4132  public String genType(Type type) throws DefinitionException {
4133    if (type instanceof Coding)
4134      return gen((Coding) type);
4135    if (type instanceof CodeableConcept)
4136      return displayCodeableConcept((CodeableConcept) type);
4137    if (type instanceof Quantity)
4138      return displayQuantity((Quantity) type);
4139    if (type instanceof Range)
4140      return displayRange((Range) type);
4141    return null;
4142  }
4143        private String gen(Extension extension) throws DefinitionException {
4144                if (extension.getValue() instanceof CodeType)
4145                        return ((CodeType) extension.getValue()).getValue();
4146                if (extension.getValue() instanceof Coding)
4147                        return gen((Coding) extension.getValue());
4148
4149          throw new DefinitionException("Unhandled type "+extension.getValue().getClass().getName());
4150  }
4151
4152        public String gen(CodeableConcept code) {
4153                if (code == null)
4154                return null;
4155                if (code.hasText())
4156                        return code.getText();
4157                if (code.hasCoding())
4158                        return gen(code.getCoding().get(0));
4159                return null;
4160        }
4161
4162        public String gen(Coding code) {
4163          if (code == null)
4164                return null;
4165          if (code.hasDisplayElement())
4166                return code.getDisplay();
4167          if (code.hasCodeElement())
4168                return code.getCode();
4169          return null;
4170  }
4171
4172  public boolean generate(ResourceContext rcontext, StructureDefinition sd, Set<String> outputTracker) throws EOperationOutcome, FHIRException, IOException {
4173    ProfileUtilities pu = new ProfileUtilities(context, null, pkp);
4174    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
4175    x.getChildNodes().add(pu.generateTable(definitionsTarget, sd, true, destDir, false, sd.getId(), false, corePath, "", false, false, outputTracker));
4176    inject(sd, x, NarrativeStatus.GENERATED);
4177    return true;
4178  }
4179  public boolean generate(ResourceContext rcontext, ImplementationGuide ig) throws EOperationOutcome, FHIRException, IOException {
4180    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
4181    x.h2().addText(ig.getName());
4182    x.para().tx("The official URL for this implementation guide is: ");
4183    x.pre().tx(ig.getUrl());
4184    addMarkdown(x, ig.getDescription());
4185    inject(ig, x, NarrativeStatus.GENERATED);
4186    return true;
4187  }
4188
4189  public boolean generate(ResourceContext rcontext, OperationDefinition opd) throws EOperationOutcome, FHIRException, IOException {
4190    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
4191    x.h2().addText(opd.getName());
4192    x.para().addText(Utilities.capitalize(opd.getKind().toString())+": "+opd.getName());
4193    x.para().tx("The official URL for this operation definition is: ");
4194    x.pre().tx(opd.getUrl());
4195    addMarkdown(x, opd.getDescription());
4196
4197    if (opd.getSystem())
4198      x.para().tx("URL: [base]/$"+opd.getCode());
4199    for (CodeType c : opd.getResource()) {
4200      if (opd.getType())
4201        x.para().tx("URL: [base]/"+c.getValue()+"/$"+opd.getCode());
4202      if (opd.getInstance())
4203        x.para().tx("URL: [base]/"+c.getValue()+"/[id]/$"+opd.getCode());
4204    }
4205
4206    x.para().tx("Parameters");
4207    XhtmlNode tbl = x.table( "grid");
4208    XhtmlNode tr = tbl.tr();
4209    tr.td().b().tx("Use");
4210    tr.td().b().tx("Name");
4211    tr.td().b().tx("Cardinality");
4212    tr.td().b().tx("Type");
4213    tr.td().b().tx("Binding");
4214    tr.td().b().tx("Documentation");
4215    for (OperationDefinitionParameterComponent p : opd.getParameter()) {
4216      genOpParam(rcontext, tbl, "", p);
4217    }
4218    addMarkdown(x, opd.getComment());
4219    inject(opd, x, NarrativeStatus.GENERATED);
4220    return true;
4221        }
4222
4223        private void genOpParam(ResourceContext rcontext, XhtmlNode tbl, String path, OperationDefinitionParameterComponent p) throws EOperationOutcome, FHIRException, IOException {
4224                XhtmlNode tr;
4225      tr = tbl.tr();
4226      tr.td().addText(p.getUse().toString());
4227      tr.td().addText(path+p.getName());
4228      tr.td().addText(Integer.toString(p.getMin())+".."+p.getMax());
4229      XhtmlNode td = tr.td();
4230      StructureDefinition sd = context.fetchTypeDefinition(p.getType());
4231      if (sd == null)
4232        td.tx(p.hasType() ? p.getType() : "");
4233      else if (sd.getAbstract() && p.hasExtension(ToolingExtensions.EXT_ALLOWED_TYPE)) {
4234        boolean first = true;
4235        for (Extension ex : p.getExtensionsByUrl(ToolingExtensions.EXT_ALLOWED_TYPE)) {
4236          if (first) first = false; else td.tx(" | ");
4237          String s = ex.getValue().primitiveValue();
4238          StructureDefinition sdt = context.fetchTypeDefinition(s);
4239          if (sdt == null)
4240            td.tx(p.hasType() ? p.getType() : "");
4241          else
4242            td.ah(sdt.getUserString("path")).tx(s);         
4243        }
4244      } else
4245        td.ah(sd.getUserString("path")).tx(p.hasType() ? p.getType() : "");
4246      if (p.hasSearchType()) {
4247        td.br();
4248        td.tx("(");
4249        td.ah( corePath == null ? "search.html#"+p.getSearchType().toCode() : Utilities.pathURL(corePath, "search.html#"+p.getSearchType().toCode())).tx(p.getSearchType().toCode());       
4250        td.tx(")");
4251      }
4252      td = tr.td();
4253      if (p.hasBinding() && p.getBinding().hasValueSet()) {
4254        AddVsRef(rcontext, p.getBinding().getValueSet(), td);
4255        td.tx(" ("+p.getBinding().getStrength().getDisplay()+")");
4256      }
4257      addMarkdown(tr.td(), p.getDocumentation());
4258      if (!p.hasType()) {
4259                        for (OperationDefinitionParameterComponent pp : p.getPart()) {
4260                                genOpParam(rcontext, tbl, path+p.getName()+".", pp);
4261        }
4262      }
4263    }
4264
4265        private void addMarkdown(XhtmlNode x, String text) throws FHIRFormatError, IOException, DefinitionException {
4266          if (text != null) {
4267            // 1. custom FHIR extensions
4268            while (text.contains("[[[")) {
4269              String left = text.substring(0, text.indexOf("[[["));
4270              String link = text.substring(text.indexOf("[[[")+3, text.indexOf("]]]"));
4271              String right = text.substring(text.indexOf("]]]")+3);
4272              String url = link;
4273              String[] parts = link.split("\\#");
4274              StructureDefinition p = context.fetchResource(StructureDefinition.class, parts[0]);
4275              if (p == null)
4276                p = context.fetchTypeDefinition(parts[0]);
4277              if (p == null)
4278                p = context.fetchResource(StructureDefinition.class, link);
4279              if (p != null) {
4280                url = p.getUserString("path");
4281                if (url == null)
4282                  url = p.getUserString("filename");
4283              } else
4284                throw new DefinitionException("Unable to resolve markdown link "+link);
4285
4286              text = left+"["+link+"]("+url+")"+right;
4287            }
4288
4289            // 2. markdown
4290            String s = markdown.process(Utilities.escapeXml(text), "narrative generator");
4291            XhtmlParser p = new XhtmlParser();
4292            XhtmlNode m;
4293                try {
4294                        m = p.parse("<div>"+s+"</div>", "div");
4295                } catch (org.hl7.fhir.exceptions.FHIRFormatError e) {
4296                        throw new FHIRFormatError(e.getMessage(), e);
4297                }
4298            x.getChildNodes().addAll(m.getChildNodes());
4299          }
4300  }
4301
4302  public boolean generate(ResourceContext rcontext, CompartmentDefinition cpd) {
4303    StringBuilder in = new StringBuilder();
4304    StringBuilder out = new StringBuilder();
4305    for (CompartmentDefinitionResourceComponent cc: cpd.getResource()) {
4306      CommaSeparatedStringBuilder rules = new CommaSeparatedStringBuilder();
4307      if (!cc.hasParam()) {
4308        out.append(" <li><a href=\"").append(cc.getCode().toLowerCase()).append(".html\">").append(cc.getCode()).append("</a></li>\r\n");
4309      } else if (!rules.equals("{def}")) {
4310        for (StringType p : cc.getParam())
4311          rules.append(p.asStringValue());
4312        in.append(" <tr><td><a href=\"").append(cc.getCode().toLowerCase()).append(".html\">").append(cc.getCode()).append("</a></td><td>").append(rules.toString()).append("</td></tr>\r\n");
4313      }
4314    }
4315    XhtmlNode x;
4316    try {
4317      x = new XhtmlParser().parseFragment("<div><p>\r\nThe following resources may be in this compartment:\r\n</p>\r\n" +
4318          "<table class=\"grid\">\r\n"+
4319          " <tr><td><b>Resource</b></td><td><b>Inclusion Criteria</b></td></tr>\r\n"+
4320          in.toString()+
4321          "</table>\r\n"+
4322          "<p>\r\nA resource is in this compartment if the nominated search parameter (or chain) refers to the patient resource that defines the compartment.\r\n</p>\r\n" +
4323          "<p>\r\n\r\n</p>\r\n" +
4324          "<p>\r\nThe following resources are never in this compartment:\r\n</p>\r\n" +
4325          "<ul>\r\n"+
4326          out.toString()+
4327          "</ul></div>\r\n");
4328      inject(cpd, x, NarrativeStatus.GENERATED);
4329      return true;
4330    } catch (Exception e) {
4331      e.printStackTrace();
4332      return false;
4333    }
4334  }
4335
4336  public boolean generate(ResourceContext rcontext, CapabilityStatement conf) throws FHIRFormatError, DefinitionException, IOException {
4337    XhtmlNode x = new XhtmlNode(NodeType.Element, "div");
4338    x.h2().addText(conf.getName());
4339    addMarkdown(x, conf.getDescription());
4340    if (conf.getRest().size() > 0) {
4341      CapabilityStatementRestComponent rest = conf.getRest().get(0);
4342      XhtmlNode t = x.table(null);
4343      addTableRow(t, "Mode", rest.getMode().toString());
4344      addTableRow(t, "Description", rest.getDocumentation());
4345
4346      addTableRow(t, "Transaction", showOp(rest, SystemRestfulInteraction.TRANSACTION));
4347      addTableRow(t, "System History", showOp(rest, SystemRestfulInteraction.HISTORYSYSTEM));
4348      addTableRow(t, "System Search", showOp(rest, SystemRestfulInteraction.SEARCHSYSTEM));
4349
4350      boolean hasVRead = false;
4351      boolean hasPatch = false;
4352      boolean hasDelete = false;
4353      boolean hasHistory = false;
4354      boolean hasUpdates = false;
4355      for (CapabilityStatementRestResourceComponent r : rest.getResource()) {
4356        hasVRead = hasVRead || hasOp(r, TypeRestfulInteraction.VREAD);
4357        hasPatch = hasPatch || hasOp(r, TypeRestfulInteraction.PATCH);
4358        hasDelete = hasDelete || hasOp(r, TypeRestfulInteraction.DELETE);
4359        hasHistory = hasHistory || hasOp(r, TypeRestfulInteraction.HISTORYTYPE);
4360        hasUpdates = hasUpdates || hasOp(r, TypeRestfulInteraction.HISTORYINSTANCE);
4361      }
4362      
4363      t = x.table(null);
4364      XhtmlNode tr = t.tr();
4365      tr.th().b().tx("Resource Type");
4366      tr.th().b().tx("Profile");
4367      tr.th().b().attribute("title", "GET a resource (read interaction)").tx("Read");
4368      if (hasVRead)
4369        tr.th().b().attribute("title", "GET past versions of resources (vread interaction)").tx("V-Read");
4370      tr.th().b().attribute("title", "GET all set of resources of the type (search interaction)").tx("Search");
4371      tr.th().b().attribute("title", "PUT a new resource version (update interaction)").tx("Update");
4372      if (hasPatch)
4373        tr.th().b().attribute("title", "PATCH a new resource version (patch interaction)").tx("Patch");
4374      tr.th().b().attribute("title", "POST a new resource (create interaction)").tx("Create");
4375      if (hasDelete)
4376        tr.th().b().attribute("title", "DELETE a resource (delete interaction)").tx("Delete");
4377      if (hasUpdates)
4378        tr.th().b().attribute("title", "GET changes to a resource (history interaction on instance)").tx("Updates");
4379      if (hasHistory)
4380        tr.th().b().attribute("title", "GET changes for all resources of the type (history interaction on type)").tx("History");
4381
4382      for (CapabilityStatementRestResourceComponent r : rest.getResource()) {
4383        tr = t.tr();
4384        tr.td().addText(r.getType());
4385        if (r.hasProfile()) {
4386          tr.td().ah(prefix+r.getProfile()).addText(r.getProfile());
4387        }
4388        tr.td().addText(showOp(r, TypeRestfulInteraction.READ));
4389        if (hasVRead)
4390          tr.td().addText(showOp(r, TypeRestfulInteraction.VREAD));
4391        tr.td().addText(showOp(r, TypeRestfulInteraction.SEARCHTYPE));
4392        tr.td().addText(showOp(r, TypeRestfulInteraction.UPDATE));
4393        if (hasPatch)
4394          tr.td().addText(showOp(r, TypeRestfulInteraction.PATCH));
4395        tr.td().addText(showOp(r, TypeRestfulInteraction.CREATE));
4396        if (hasDelete)
4397          tr.td().addText(showOp(r, TypeRestfulInteraction.DELETE));
4398        if (hasUpdates)
4399          tr.td().addText(showOp(r, TypeRestfulInteraction.HISTORYINSTANCE));
4400        if (hasHistory)
4401          tr.td().addText(showOp(r, TypeRestfulInteraction.HISTORYTYPE));
4402      }
4403    }
4404
4405    inject(conf, x, NarrativeStatus.GENERATED);
4406    return true;
4407  }
4408
4409  private boolean hasOp(CapabilityStatementRestResourceComponent r, TypeRestfulInteraction on) {
4410    for (ResourceInteractionComponent op : r.getInteraction()) {
4411      if (op.getCode() == on)
4412        return true;
4413    }
4414    return false;
4415  }
4416  
4417  private String showOp(CapabilityStatementRestResourceComponent r, TypeRestfulInteraction on) {
4418    for (ResourceInteractionComponent op : r.getInteraction()) {
4419      if (op.getCode() == on)
4420        return "y";
4421    }
4422    return "";
4423  }
4424
4425  private String showOp(CapabilityStatementRestComponent r, SystemRestfulInteraction on) {
4426    for (SystemInteractionComponent op : r.getInteraction()) {
4427      if (op.getCode() == on)
4428        return "y";
4429    }
4430    return "";
4431  }
4432
4433  private void addTableRow(XhtmlNode t, String name, String value) {
4434    XhtmlNode tr = t.tr();
4435    tr.td().addText(name);
4436    tr.td().addText(value);
4437  }
4438
4439  public XhtmlNode generateDocumentNarrative(Bundle feed) {
4440    /*
4441     When the document is presented for human consumption, applications must present the collated narrative portions of the following resources in order:
4442     * The Composition resource
4443     * The Subject resource
4444     * Resources referenced in the section.content
4445     */
4446    XhtmlNode root = new XhtmlNode(NodeType.Element, "div");
4447    Composition comp = (Composition) feed.getEntry().get(0).getResource();
4448    root.getChildNodes().add(comp.getText().getDiv());
4449    Resource subject = ResourceUtilities.getById(feed, null, comp.getSubject().getReference());
4450    if (subject != null && subject instanceof DomainResource) {
4451      root.hr();
4452      root.getChildNodes().add(((DomainResource)subject).getText().getDiv());
4453    }
4454    List<SectionComponent> sections = comp.getSection();
4455    renderSections(feed, root, sections, 1);
4456    return root;
4457  }
4458
4459  private void renderSections(Bundle feed, XhtmlNode node, List<SectionComponent> sections, int level) {
4460    for (SectionComponent section : sections) {
4461      node.hr();
4462      if (section.hasTitleElement())
4463        node.addTag("h"+Integer.toString(level)).addText(section.getTitle());
4464//      else if (section.hasCode())
4465//        node.addTag("h"+Integer.toString(level)).addText(displayCodeableConcept(section.getCode()));
4466
4467//      if (section.hasText()) {
4468//        node.getChildNodes().add(section.getText().getDiv());
4469//      }
4470//
4471//      if (!section.getSection().isEmpty()) {
4472//        renderSections(feed, node.addTag("blockquote"), section.getSection(), level+1);
4473//      }
4474    }
4475  }
4476
4477
4478  public class ObservationNode {
4479    private String ref;
4480    private ResourceWrapper obs;
4481    private List<ObservationNode> contained = new ArrayList<NarrativeGenerator.ObservationNode>();
4482  }
4483
4484  public XhtmlNode generateDiagnosticReport(ResourceWrapper dr) {
4485    XhtmlNode root = new XhtmlNode(NodeType.Element, "div");
4486    XhtmlNode h2 = root.h2();
4487    displayCodeableConcept(h2, getProperty(dr, "code").value());
4488    h2.tx(" ");
4489    PropertyWrapper pw = getProperty(dr, "category");
4490    if (valued(pw)) {
4491      h2.tx("(");
4492      displayCodeableConcept(h2, pw.value());
4493      h2.tx(") ");
4494    }
4495    displayDate(h2, getProperty(dr, "issued").value());
4496
4497    XhtmlNode tbl = root.table( "grid");
4498    XhtmlNode tr = tbl.tr();
4499    XhtmlNode tdl = tr.td();
4500    XhtmlNode tdr = tr.td();
4501    populateSubjectSummary(tdl, getProperty(dr, "subject").value());
4502    tdr.b().tx("Report Details");
4503    tdr.br();
4504    pw = getProperty(dr, "perfomer");
4505    if (valued(pw)) {
4506      tdr.addText(pluralise("Performer", pw.getValues().size())+":");
4507      for (BaseWrapper v : pw.getValues()) {
4508        tdr.tx(" ");
4509        displayReference(tdr, v);
4510      }
4511      tdr.br();
4512    }
4513    pw = getProperty(dr, "identifier");
4514    if (valued(pw)) {
4515      tdr.addText(pluralise("Identifier", pw.getValues().size())+":");
4516      for (BaseWrapper v : pw.getValues()) {
4517        tdr.tx(" ");
4518        displayIdentifier(tdr, v);
4519      }
4520      tdr.br();
4521    }
4522    pw = getProperty(dr, "request");
4523    if (valued(pw)) {
4524      tdr.addText(pluralise("Request", pw.getValues().size())+":");
4525      for (BaseWrapper v : pw.getValues()) {
4526        tdr.tx(" ");
4527        displayReferenceId(tdr, v);
4528      }
4529      tdr.br();
4530    }
4531
4532    pw = getProperty(dr, "result");
4533    if (valued(pw)) {
4534      List<ObservationNode> observations = fetchObservations(pw.getValues());
4535      buildObservationsTable(root, observations);
4536    }
4537
4538    pw = getProperty(dr, "conclusion");
4539    if (valued(pw))
4540      displayText(root.para(), pw.value());
4541
4542    pw = getProperty(dr, "result");
4543    if (valued(pw)) {
4544      XhtmlNode p = root.para();
4545      p.b().tx("Coded Diagnoses :");
4546      for (BaseWrapper v : pw.getValues()) {
4547        tdr.tx(" ");
4548        displayCodeableConcept(tdr, v);
4549      }
4550    }
4551    return root;
4552  }
4553
4554  private void buildObservationsTable(XhtmlNode root, List<ObservationNode> observations) {
4555    XhtmlNode tbl = root.table( "none");
4556    for (ObservationNode o : observations) {
4557      addObservationToTable(tbl, o, 0);
4558    }
4559  }
4560
4561  private void addObservationToTable(XhtmlNode tbl, ObservationNode o, int i) {
4562    XhtmlNode tr = tbl.tr();
4563    if (o.obs == null) {
4564      XhtmlNode td = tr.td().colspan("6");
4565      td.i().tx("This Observation could not be resolved");
4566    } else {
4567      addObservationToTable(tr, o.obs, i);
4568      // todo: contained observations
4569    }
4570    for (ObservationNode c : o.contained) {
4571      addObservationToTable(tbl, c, i+1);
4572    }
4573  }
4574
4575  private void addObservationToTable(XhtmlNode tr, ResourceWrapper obs, int i) {
4576    // TODO Auto-generated method stub
4577
4578    // code (+bodysite)
4579    XhtmlNode td = tr.td();
4580    PropertyWrapper pw = getProperty(obs, "result");
4581    if (valued(pw)) {
4582      displayCodeableConcept(td, pw.value());
4583    }
4584    pw = getProperty(obs, "bodySite");
4585    if (valued(pw)) {
4586      td.tx(" (");
4587      displayCodeableConcept(td, pw.value());
4588      td.tx(")");
4589    }
4590
4591    // value / dataAbsentReason (in red)
4592    td = tr.td();
4593    pw = getProperty(obs, "value[x]");
4594    if (valued(pw)) {
4595      if (pw.getTypeCode().equals("CodeableConcept"))
4596        displayCodeableConcept(td, pw.value());
4597      else if (pw.getTypeCode().equals("string"))
4598        displayText(td, pw.value());
4599      else
4600        td.addText(pw.getTypeCode()+" not rendered yet");
4601    }
4602
4603    // units
4604    td = tr.td();
4605    td.tx("to do");
4606
4607    // reference range
4608    td = tr.td();
4609    td.tx("to do");
4610
4611    // flags (status other than F, interpretation, )
4612    td = tr.td();
4613    td.tx("to do");
4614
4615    // issued if different to DR
4616    td = tr.td();
4617    td.tx("to do");
4618  }
4619
4620  private boolean valued(PropertyWrapper pw) {
4621    return pw != null && pw.hasValues();
4622  }
4623
4624  private void displayText(XhtmlNode c, BaseWrapper v) {
4625    c.addText(v.toString());
4626  }
4627
4628  private String pluralise(String name, int size) {
4629    return size == 1 ? name : name+"s";
4630  }
4631
4632  private void displayIdentifier(XhtmlNode c, BaseWrapper v) {
4633    String hint = "";
4634    PropertyWrapper pw = v.getChildByName("type");
4635    if (valued(pw)) {
4636      hint = genCC(pw.value());
4637    } else {
4638      pw = v.getChildByName("system");
4639      if (valued(pw)) {
4640        hint = pw.value().toString();
4641      }
4642    }
4643    displayText(c.span(null, hint), v.getChildByName("value").value());
4644  }
4645
4646  private String genCoding(BaseWrapper value) {
4647    PropertyWrapper pw = value.getChildByName("display");
4648    if (valued(pw))
4649      return pw.value().toString();
4650    pw = value.getChildByName("code");
4651    if (valued(pw))
4652      return pw.value().toString();
4653    return "";
4654  }
4655
4656  private String genCC(BaseWrapper value) {
4657    PropertyWrapper pw = value.getChildByName("text");
4658    if (valued(pw))
4659      return pw.value().toString();
4660    pw = value.getChildByName("coding");
4661    if (valued(pw))
4662      return genCoding(pw.getValues().get(0));
4663    return "";
4664  }
4665
4666  private void displayReference(XhtmlNode c, BaseWrapper v) {
4667    c.tx("to do");
4668  }
4669
4670
4671  private void displayDate(XhtmlNode c, BaseWrapper baseWrapper) {
4672    c.tx("to do");
4673  }
4674
4675  private void displayCodeableConcept(XhtmlNode c, BaseWrapper property) {
4676    c.tx("to do");
4677  }
4678
4679  private void displayReferenceId(XhtmlNode c, BaseWrapper v) {
4680    c.tx("to do");
4681  }
4682
4683  private PropertyWrapper getProperty(ResourceWrapper res, String name) {
4684    for (PropertyWrapper t : res.children()) {
4685      if (t.getName().equals(name))
4686        return t;
4687    }
4688    return null;
4689  }
4690
4691  private void populateSubjectSummary(XhtmlNode container, BaseWrapper subject) {
4692    ResourceWrapper r = fetchResource(subject);
4693    if (r == null)
4694      container.tx("Unable to get Patient Details");
4695    else if (r.getName().equals("Patient"))
4696      generatePatientSummary(container, r);
4697    else
4698      container.tx("Not done yet");
4699  }
4700
4701  private void generatePatientSummary(XhtmlNode c, ResourceWrapper r) {
4702    c.tx("to do");
4703  }
4704
4705  private ResourceWrapper fetchResource(BaseWrapper subject) {
4706    if (resolver == null)
4707      return null;
4708    String url = subject.getChildByName("reference").value().toString();
4709    ResourceWithReference rr = resolver.resolve(url);
4710    return rr == null ? null : rr.resource;
4711  }
4712
4713  private List<ObservationNode> fetchObservations(List<BaseWrapper> list) {
4714    return new ArrayList<NarrativeGenerator.ObservationNode>();
4715  }
4716
4717  public XhtmlNode renderBundle(Bundle b) throws FHIRException {
4718    if (b.getType() == BundleType.DOCUMENT) {
4719      if (!b.hasEntry() || !(b.getEntryFirstRep().hasResource() && b.getEntryFirstRep().getResource() instanceof Composition))
4720        throw new FHIRException("Invalid document - first entry is not a Composition");
4721      Composition dr = (Composition) b.getEntryFirstRep().getResource();
4722      return dr.getText().getDiv();
4723    } else  {
4724      XhtmlNode root = new XhtmlNode(NodeType.Element, "div");
4725      root.para().addText("Bundle "+b.getId()+" of type "+b.getType().toCode());
4726      int i = 0;
4727      for (BundleEntryComponent be : b.getEntry()) {
4728        i++;
4729        if (be.hasResource() && be.getResource().hasId())
4730          root.an(be.getResource().getResourceType().name().toLowerCase() + "_" + be.getResource().getId());
4731        root.hr();
4732        root.para().addText("Entry "+Integer.toString(i)+(be.hasFullUrl() ? " - Full URL = " + be.getFullUrl() : ""));
4733        if (be.hasRequest())
4734          renderRequest(root, be.getRequest());
4735        if (be.hasSearch())
4736          renderSearch(root, be.getSearch());
4737        if (be.hasResponse())
4738          renderResponse(root, be.getResponse());
4739        if (be.hasResource()) {
4740          root.para().addText("Resource "+be.getResource().fhirType()+":");
4741          if (be.hasResource() && be.getResource() instanceof DomainResource) {
4742            DomainResource dr = (DomainResource) be.getResource();
4743            if ( dr.getText().hasDiv())
4744              root.blockquote().getChildNodes().addAll(dr.getText().getDiv().getChildNodes());
4745          }
4746        }
4747      }
4748      return root;
4749    }
4750  }
4751
4752  private void renderSearch(XhtmlNode root, BundleEntrySearchComponent search) {
4753    StringBuilder b = new StringBuilder();
4754    b.append("Search: ");
4755    if (search.hasMode())
4756      b.append("mode = "+search.getMode().toCode());
4757    if (search.hasScore()) {
4758      if (search.hasMode())
4759        b.append(",");
4760      b.append("score = "+search.getScore());
4761    }
4762    root.para().addText(b.toString());    
4763  }
4764
4765  private void renderResponse(XhtmlNode root, BundleEntryResponseComponent response) {
4766    root.para().addText("Request:");
4767    StringBuilder b = new StringBuilder();
4768    b.append(response.getStatus()+"\r\n");
4769    if (response.hasLocation())
4770      b.append("Location: "+response.getLocation()+"\r\n");
4771    if (response.hasEtag())
4772      b.append("E-Tag: "+response.getEtag()+"\r\n");
4773    if (response.hasLastModified())
4774      b.append("LastModified: "+response.getEtag()+"\r\n");
4775    root.pre().addText(b.toString());    
4776  }
4777
4778  private void renderRequest(XhtmlNode root, BundleEntryRequestComponent request) {
4779    root.para().addText("Response:");
4780    StringBuilder b = new StringBuilder();
4781    b.append(request.getMethod()+" "+request.getUrl()+"\r\n");
4782    if (request.hasIfNoneMatch())
4783      b.append("If-None-Match: "+request.getIfNoneMatch()+"\r\n");
4784    if (request.hasIfModifiedSince())
4785      b.append("If-Modified-Since: "+request.getIfModifiedSince()+"\r\n");
4786    if (request.hasIfMatch())
4787      b.append("If-Match: "+request.getIfMatch()+"\r\n");
4788    if (request.hasIfNoneExist())
4789      b.append("If-None-Exist: "+request.getIfNoneExist()+"\r\n");
4790    root.pre().addText(b.toString());    
4791  }
4792
4793  public XhtmlNode renderBundle(org.hl7.fhir.r5.elementmodel.Element element) throws FHIRException {
4794    XhtmlNode root = new XhtmlNode(NodeType.Element, "div");
4795    for (Base b : element.listChildrenByName("entry")) {
4796      org.hl7.fhir.r5.elementmodel.Element r = ((org.hl7.fhir.r5.elementmodel.Element) b).getNamedChild("resource");
4797      if (r!=null) {
4798        XhtmlNode c = getHtmlForResource(r);
4799        if (c != null)
4800          root.getChildNodes().addAll(c.getChildNodes());
4801        root.hr();
4802      }
4803    }
4804    return root;
4805  }
4806
4807  private XhtmlNode getHtmlForResource(org.hl7.fhir.r5.elementmodel.Element element) {
4808    org.hl7.fhir.r5.elementmodel.Element text = element.getNamedChild("text");
4809    if (text == null)
4810      return null;
4811    org.hl7.fhir.r5.elementmodel.Element div = text.getNamedChild("div");
4812    if (div == null)
4813      return null;
4814    else
4815      return div.getXhtml();
4816  }
4817
4818  public String getDefinitionsTarget() {
4819    return definitionsTarget;
4820  }
4821
4822  public void setDefinitionsTarget(String definitionsTarget) {
4823    this.definitionsTarget = definitionsTarget;
4824  }
4825
4826  public String getCorePath() {
4827    return corePath;
4828  }
4829
4830  public void setCorePath(String corePath) {
4831    this.corePath = corePath;
4832  }
4833
4834  public String getDestDir() {
4835    return destDir;
4836  }
4837
4838  public void setDestDir(String destDir) {
4839    this.destDir = destDir;
4840  }
4841
4842  public ProfileKnowledgeProvider getPkp() {
4843    return pkp;
4844  }
4845
4846  public NarrativeGenerator setPkp(ProfileKnowledgeProvider pkp) {
4847    this.pkp = pkp;
4848    return this;
4849  }
4850
4851  public boolean isPretty() {
4852    return pretty;
4853  }
4854
4855  public NarrativeGenerator setPretty(boolean pretty) {
4856    this.pretty = pretty;
4857    return this;
4858  }
4859
4860  public boolean isCanonicalUrlsAsLinks() {
4861    return canonicalUrlsAsLinks;
4862  }
4863
4864  @Override
4865  public void setCanonicalUrlsAsLinks(boolean canonicalUrlsAsLinks) {
4866    this.canonicalUrlsAsLinks = canonicalUrlsAsLinks;
4867  }
4868
4869  public String getSnomedEdition() {
4870    return snomedEdition;
4871  }
4872
4873  public NarrativeGenerator setSnomedEdition(String snomedEdition) {
4874    this.snomedEdition = snomedEdition;
4875    return this;
4876  }
4877
4878  public TerminologyServiceOptions getTerminologyServiceOptions() {
4879    return terminologyServiceOptions;
4880  }
4881
4882  public void setTerminologyServiceOptions(TerminologyServiceOptions terminologyServiceOptions) {
4883    this.terminologyServiceOptions = terminologyServiceOptions;
4884  }
4885
4886  public boolean isNoSlowLookup() {
4887    return noSlowLookup;
4888  }
4889
4890  public void setNoSlowLookup(boolean noSlowLookup) {
4891    this.noSlowLookup = noSlowLookup;
4892  }
4893
4894  public List<String> getCodeSystemPropList() {
4895    return codeSystemPropList;
4896  }
4897
4898
4899  
4900}