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