/*
 * Copyright 2011 NEHTA
 *
 * Licensed under the NEHTA Open Source (Apache) License; you may not use this
 * file except in compliance with the License. A copy of the License is in the
 * 'license.txt' file, which should be provided with this work.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Nehta.HL7.CDA;
using Nehta.VendorLibrary.CDA.Generator.Enums;
using Nehta.VendorLibrary.CDA.SCSModel.Common.Entities;
using Nehta.VendorLibrary.Common;
using Nehta.VendorLibrary.CDA.Generator;
using Nehta.VendorLibrary.CDA.Common.Enums;
using Nehta.VendorLibrary.CDA.Common;
using Nehta.VendorLibrary.CDA.SCSModel;
using Nehta.VendorLibrary.CDA.SCSModel.Common;

namespace Nehta.VendorLibrary.CDA.Sample
{
    /// <summary>
    /// This project is intended to demonstrate how an EventSummary CDA document can be created.
    /// 
    /// The project contains two samples, the first is designed to create a fully populated CDA document, including
    /// all of the optional sections and entries. The second sample only populates the mandatory sections and entries.
    /// 
    /// The CDA model is split into three distinct sections, each of which needs to be created via the 
    /// EventSummary class, and then populated with data as appropriate. The three sections that need to be
    /// created and hydrated with data are:
    /// 
    ///     CDA Context (Clinical Document Architecture - Context)
    ///     SCS Context (Structured Document Template - Context)
    ///     SCS Content (Structured Document Template - Content)
    /// 
    /// The CDA Context typically contains information that is to be represented within the header of the document
    /// that is not encapsulated with the SCS context.
    /// E.g. Generic CDA sections or entries; for example custodian.
    /// 
    /// The SCS Context typically contains information that is to be represented within the header of the document
    /// and relates specifically to the type of document that is to be created.
    /// E.g. E-Referral specific CDA sections or entries; for example Subject of Care.
    /// 
    /// The SCS Content typically contains information that is to be represented with the body of the document.
    /// </summary>
    public class EventSummarySample
    {
        #region Properties

        public static string OutputFolderPath { get; set; }

        public static String OutputFileNameAndPath
        {
            get
            {
                return OutputFolderPath + @"\EventSummary.xml";
            }
        }

        public static String ImageFileNameAndPath
        {
            get
            {
                return OutputFolderPath + @"\x-ray.jpg";
            }
        }

        public static String PitNameAndPath
        {
            get
            {
                return OutputFolderPath + @"\PIT.txt";
            }
        }

        public static String StructuredFileAttachment
        {
            get
            {
                return OutputFolderPath + @"\attachment.pdf";
            }
        }

        public static String ResultFileNameAndPath
        {
            get
            {
                return OutputFolderPath + @"\path1234.pdf";
            }
        }

        // Note: Place this in any string field and and this will insert a break
        private const String DELIMITERBREAK = "<BR>";

        #endregion

        /// <summary>
        /// This sample populates only the mandatory sections / entries
        /// </summary>
        public XmlDocument MinPopulatedEventSummary(string fileName)
        {
            XmlDocument xmlDoc = null;

            var eEventSummary = PopulatedEventSummary(true);

            try
            {
                CDAGenerator.NarrativeGenerator = new CDANarrativeGenerator();

                //Pass the Event Summary model into the GenerateEventSummary method 
                xmlDoc = CDAGenerator.GenerateEventSummary(eEventSummary);

                using (var writer = XmlWriter.Create(OutputFolderPath + @"\" + fileName, new XmlWriterSettings { Indent = true }))
                {
                    if (!fileName.IsNullOrEmptyWhitespace()) xmlDoc.Save(writer);
                }
            }
            catch (ValidationException ex)
            {
                //Catch any validation exceptions
                var validationMessages = ex.GetMessagesString();

                //Handle any validation errors as appropriate.
                throw;
            }

            return xmlDoc;
        }

        /// <summary>
        /// This example populates only the mandatory Sections / Entries; as a result this sample omits all
        /// of the content within the body of the CDA document; as each of the sections within the body
        /// are optional.
        /// </summary>
        public XmlDocument PopulateEventSummarySample_1A(string fileName)
        {
            XmlDocument xmlDoc = null;

            var document = PopulatedEventSummary(true);
            document.SCSContent = EventSummary.CreateSCSContent();

            document.IncludeLogo = false;

            var structuredBodyFileList = new List<ExternalData>();

            var structuredBodyFile = BaseCDAModel.CreateStructuredBodyFile();
            structuredBodyFile.Caption = "Structured Body File";
            structuredBodyFile.ExternalDataMediaType = MediaType.PDF;
            structuredBodyFile.Path = StructuredFileAttachment;
            structuredBodyFileList.Add(structuredBodyFile);

            document.SCSContent.StructuredBodyFiles = structuredBodyFileList;

            try
            {
                CDAGenerator.NarrativeGenerator = new CDANarrativeGenerator();

                //Pass the document model into the Generate method 
                xmlDoc = CDAGenerator.GenerateEventSummary(document);

                using (var writer = XmlWriter.Create(OutputFolderPath + @"\" + fileName, new XmlWriterSettings() { Indent = true }))
                {
                    if (!fileName.IsNullOrEmptyWhitespace()) xmlDoc.Save(writer);
                }
            }
            catch (ValidationException ex)
            {
                //Catch any validation exceptions
                var validationMessages = ex.GetMessagesString();

                //Handle any validation errors as appropriate.
                throw;
            }

            return xmlDoc;
        }

        /// <summary>
        /// This sample populates both the mandatory and optional Sections / Entries; as a result this sample
        /// includes all of the sections within the body and each section includes at least one example for 
        /// each of its optional entries
        /// </summary>
        public XmlDocument MaxPopulatedEventSummary(string fileName)
        {
            XmlDocument xmlDoc = null;

            var eEventSummary = PopulatedEventSummary(false);

            try
            {
                CDAGenerator.NarrativeGenerator = new CDANarrativeGenerator();

                //Pass the Event Summary model into the GenerateEventSummary method 
                xmlDoc = CDAGenerator.GenerateEventSummary(eEventSummary);

                using (var writer = XmlWriter.Create(OutputFolderPath + @"\" + fileName, new XmlWriterSettings() { Indent = true }))
                {
                    if (!fileName.IsNullOrEmptyWhitespace()) xmlDoc.Save(writer);
                }
            }
            catch (ValidationException ex)
            {
                //Catch any validation exceptions
                var validationMessages = ex.GetMessagesString();

                //Handle any validation errors as appropriate.
                throw;
            }

            return xmlDoc;
        }

        /// <summary>
        /// This example populates only the mandatory Sections / Entries; as a result this sample ommits all
        /// of the non mandatory content.
        /// </summary>
        public XmlDocument PopulatedEventSummary()
        {
            XmlDocument xmlDoc = null;

            var eEventSummary = PopulatedEventSummary(true);

            try
            {
                CDAGenerator.NarrativeGenerator = new CDANarrativeGenerator();

                xmlDoc = CDAGenerator.GenerateEventSummary(eEventSummary);

                xmlDoc.Save(OutputFileNameAndPath);
            }
            catch (ValidationException ex)
            {
                //Catch any validation exceptions
                var validationMessages = ex.GetMessagesString();

                //Handle any validation errors as appropriate.
            }
            return xmlDoc;
        }

        #region Private Test Methods

        /// <summary>
        /// This sample populates both the mandatory and optional Sections / Entries depenting on the  
        /// mandatorySectionsOnly boolean
        /// </summary>
        internal static EventSummary PopulatedEventSummary(Boolean mandatorySectionsOnly)
        {
            var eventSummary = EventSummary.CreateEventSummary();

            // Include Logo
            eventSummary.IncludeLogo = true;

            // Set Creation Time
            eventSummary.DocumentCreationTime = new ISO8601DateTime(DateTime.Now);

            #region Setup and populate the CDA context model

            // Setup and populate the CDA context model
            var cdaContext = EventSummary.CreateCDAContext();
            // Document Id
            cdaContext.DocumentId = BaseCDAModel.CreateIdentifier(BaseCDAModel.CreateGuid(), null);
            // Set Id  
            cdaContext.SetId = BaseCDAModel.CreateIdentifier(BaseCDAModel.CreateGuid(), null);
            // CDA Context Version
            cdaContext.Version = "1";

            // Custodian
            cdaContext.Custodian = EventSummary.CreateCustodian();
            GenericObjectReuseSample.HydrateCustodian(cdaContext.Custodian, mandatorySectionsOnly);

            cdaContext.LegalAuthenticator = EventSummary.CreateLegalAuthenticator();
            GenericObjectReuseSample.HydrateAuthenticator(cdaContext.LegalAuthenticator, mandatorySectionsOnly);

            eventSummary.CDAContext = cdaContext;
            #endregion

            #region Setup and Populate the SCS Context model
            // Setup and Populate the SCS Context model

            eventSummary.SCSContext = EventSummary.CreateSCSContext();

            eventSummary.SCSContext.Author = EventSummary.CreateAuthor();
            GenericObjectReuseSample.HydrateAuthor(eventSummary.SCSContext.Author, mandatorySectionsOnly);

            eventSummary.SCSContext.SubjectOfCare = EventSummary.CreateSubjectOfCare();
            GenericObjectReuseSample.HydrateSubjectofCare(eventSummary.SCSContext.SubjectOfCare, mandatorySectionsOnly);

            if (!mandatorySectionsOnly)
            {
                eventSummary.SCSContext.EncounterPeriod = BaseCDAModel.CreateInterval("12", TimeUnitOfMeasure.Month);
            }
              else
            {
                eventSummary.SCSContext.EncounterPeriodNullFlavor = NullFlavour.NegativeInfinity;
            }

            #endregion

            #region Setup and populate the SCS Content model
            // Setup and populate the SCS Content model
            eventSummary.SCSContent = EventSummary.CreateSCSContent();

            if (!mandatorySectionsOnly)
            {
                eventSummary.SCSContent.EventDetails = CreateEventDetails();

                // Adverse reactions
                eventSummary.SCSContent.AdverseReactions = CreateAdverseReactions();

                // Medications
                eventSummary.SCSContent.Medications = CreateMedications();

                // Medical history
                eventSummary.SCSContent.DiagnosesIntervention = CreateDiagnosesIntervention();

                // Immunisations
                eventSummary.SCSContent.Immunisations = CreateImmunisations();

                // Diagnostic Investigations
                eventSummary.SCSContent.DiagnosticInvestigations = CreateDiagnosticInvestigations(mandatorySectionsOnly);

            }

            #endregion

            return eventSummary;
        }

        /// <summary>
        /// Creates and Hydrates a Reference Range
        /// </summary>
        /// <param name="code">The Code</param>
        /// <param name="name">The Name</param>
        /// <param name="units">The Unit</param>
        /// <param name="high">The high value</param>
        /// <param name="low">The Low Value</param>
        /// <returns>A Hydrated ResultValueReferenceRangeDetail object</returns>
        private static ResultValueReferenceRangeDetail CreateReferenceRange(String code, String name, String units, String high, String low)
        {
            var resultValueReferenceRangeDetail = EventSummary.CreateResultValueReferenceRangeDetail();
            resultValueReferenceRangeDetail.Range = EventSummary.CreateQuantityRange();
            resultValueReferenceRangeDetail.Range.High = high;
            resultValueReferenceRangeDetail.Range.Low = low;
            resultValueReferenceRangeDetail.Range.Units = units;
            resultValueReferenceRangeDetail.ResultValueReferenceRangeMeaning = EventSummary.CreateResultValueReferenceRangeMeaning
                                                                                (
                                                                                    code,
                                                                                    CodingSystem.SNOMED,
                                                                                    name,
                                                                                    null,
                                                                                    null
                                                                                );

            return resultValueReferenceRangeDetail;
        }

        /// <summary>
        /// Creates and Hydrates a PhysicalDetails object
        /// </summary>
        /// <param name="value">The Value</param>
        /// <param name="units">The Unit</param>
        /// <returns>A Hydrated PhysicalDetails object</returns>
        private static PhysicalDetails CreatePhysicalDetails(String value, String units)
        {
            PhysicalDetails physicalDetails = null;

            if (!value.IsNullOrEmptyWhitespace() && !units.IsNullOrEmptyWhitespace())
            {
                physicalDetails = EventSummary.CreatePhysicalDetails();

                physicalDetails.Volume = EventSummary.CreateQuantity();
                physicalDetails.Volume.Value = value;
                physicalDetails.Volume.Units = units;
            }


            return physicalDetails;
        }

        /// <summary>
        /// Creates and Hydrates Event Details
        /// </summary>
        /// <returns>A Hydrated IImagingExaminationResultDischargeSummary object</returns>
        private static EventDetails CreateEventDetails()
        {
            var eventDetails = EventSummary.CreateEventDetails();
            eventDetails.ClinicalSynopsisDescription = EventSummary.CreateReasonForEncounterDescription("35933005", CodingSystem.SNOMED, "laceration", "laceration", null);
            return eventDetails;
        }

        /// <summary>
        /// Creates and Hydrates the immunisations section for the Event Summary
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated Event Summary object</returns>
        private static List<IImmunisation> CreateImmunisations()
        {
            var immunisationList = new List<IImmunisation>
            {
                CreateImmunisation(DateTime.Parse("22 Dec 2009"), "75071011000036107", CodingSystem.SNOMED, "IPV (inactivated poliovirus vaccine)", null),
                CreateImmunisation(DateTime.Parse("10 Sep 2010"), "92813511000036100", CodingSystem.SNOMED, "Meningitec (Meningococcal)", null),
                CreateImmunisation(DateTime.Parse("3 Oct 2010"), "58818811000066100", CodingSystem.SNOMED, "Fluvax (Influenza)", 1)
            };

            return immunisationList;
        }

      /// <summary>
      /// Creates an immunisation.
      /// </summary>
      /// <param name="date">Date of immunisation.</param>
      /// <param name="code">Code of immunisation.</param>
      /// <param name="codingSystem">Coding system for the code.</param>
      /// <param name="name">Name of immunisation.</param>
      /// <param name="sequenceNumber">The immunisation sequence number </param>
      /// <returns>Created immunisation.</returns>
      private static IImmunisation CreateImmunisation(DateTime date, string code, CodingSystem codingSystem, string name, int? sequenceNumber)
        {
            var immunisation = EventSummary.CreateImmunisation();
            immunisation.DateTime = new ISO8601DateTime(date);
            immunisation.Medicine = EventSummary.CreateMedicine(code, codingSystem, name, null, null);
            immunisation.SequenceNumber = sequenceNumber;
            return immunisation;
        }

        /// <summary>
        /// Creates and Hydrates the Medications section for the Event Summary
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated List of Medications</returns>
        private static List<IMedicationItem> CreateMedications()
        {
            var medicationList = new List<IMedicationItem>
                                     {
                                         CreateMedication("23641011000036102", "paracetamol 500 mg + codeine phosphate 30 mg tablet", NullFlavour.NegativeInfinity, NullFlavour.PositiveInfinity, NullFlavour.NoInformation),
                                         CreateMedication("23641011000036103", "panadol 1mg tablet", null, null, null)
                                     };

            return medicationList;
        }

      /// <summary>
      /// Creates a medication item.
      /// </summary>
      /// <param name="code">Medication code.</param>
      /// <param name="name">Medication name.</param>
      /// <param name="directionsNullFlavour">The Directions Null Flavour</param>
      /// <param name="recomendationOrChangeNullFlavour">The Recomendation Or Change Null Flavour</param>
      /// <param name="changeTypeNullFlavour">The Change Type Null Flavour</param>
      /// <returns></returns>
      private static IMedicationItem CreateMedication(string code, string name, NullFlavour? directionsNullFlavour, NullFlavour? recomendationOrChangeNullFlavour, NullFlavour? changeTypeNullFlavour)
        {
            IMedicationItem medication = EventSummary.CreateMedication();

            if (directionsNullFlavour.HasValue)
              medication.DirectionsNullFlavour = directionsNullFlavour;
            else
              medication.Directions = "As directed by packaging.";

            if (recomendationOrChangeNullFlavour.HasValue)
              medication.RecommendationOrChangeNullFlavour = recomendationOrChangeNullFlavour;
            else
              medication.RecommendationOrChange = RecomendationOrChange.TheChangeHasBeenMade;

            if (changeTypeNullFlavour.HasValue)
              medication.ChangeTypeNullFlavour = changeTypeNullFlavour;
            else
              medication.ChangeType = ChangeType.Unchanged;

            medication.ChangeDescription = "ChangeDescription";
            medication.ChangeReason = "ChangeReason";
            medication.ClinicalIndication = "ClinicalIndication";
            medication.Comment = "Comment";

            medication.Medicine = EventSummary.CreateMedicine
                (
                    code,
                    CodingSystem.AMT,
                    name,
                    null,
                    null
                );

            return medication;
        }

        /// <summary>
        /// Creates and Hydrates the Medications section for the Event Summary
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated List of RequestedService</returns>
        private static List<RequestedService> CreateRequestedService(Boolean mandatorySectionsOnly)
        {
            var requestedServiceList = new List<RequestedService>();

            // Create Service Provider for a Person
            var requestedServicePerson = EventSummary.CreateRequestedService();
            requestedServicePerson.ServiceCommencementWindow = EventSummary.CreateInterval(
                new ISO8601DateTime(DateTime.Now, ISO8601DateTime.Precision.Day), 
                new ISO8601DateTime(DateTime.Now.AddMonths(6), ISO8601DateTime.Precision.Day));
            requestedServicePerson.RequestedServiceDescription = EventSummary.CreateRequestedServiceDescription("39818891000056100", CodingSystem.NCTIS, "Requested Service Description", null, null);
            requestedServicePerson.ServiceBookingStatus = EventTypes.Definition;
            requestedServicePerson.SubjectOfCareInstructionDescription = "Subject Of Care Instruction Description";
            requestedServicePerson.RequestedServiceDateTime = new ISO8601DateTime(DateTime.Now.AddDays(4), ISO8601DateTime.Precision.Day);
            requestedServicePerson.ServiceProvider = CreateServiceProviderPerson(mandatorySectionsOnly);

            // Add to list
            requestedServiceList.Add(requestedServicePerson);

            // Create Service Provider for a Organisation
            var requestedServiceOrganisation = EventSummary.CreateRequestedService();
            requestedServiceOrganisation.ServiceScheduled = new ISO8601DateTime(DateTime.Now);
            requestedServiceOrganisation.RequestedServiceDescription = EventSummary.CreateRequestedServiceDescription("39818891000056100", CodingSystem.NCTIS, "Requested Service Description", null, null);
            requestedServiceOrganisation.ServiceBookingStatus = EventTypes.Intent;
            requestedServiceOrganisation.SubjectOfCareInstructionDescription = "Subject Of Care Instruction Description";
            requestedServiceOrganisation.RequestedServiceDateTime = new ISO8601DateTime(DateTime.Now.AddDays(4));
            requestedServiceOrganisation.ServiceProvider = CreateServiceProviderOrganisation(mandatorySectionsOnly);

            // Add to list
            requestedServiceList.Add(requestedServiceOrganisation);

            return requestedServiceList;
        }

        /// <summary>
        /// Creates and Hydrates a Service Provider Organisation
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated IParticipationHealthProfessional object</returns>
        private static IParticipationServiceProvider CreateServiceProviderOrganisation(Boolean mandatorySectionsOnly)
        {
            var serviceProvider = EventSummary.CreateServiceProvider();

            serviceProvider.Participant = EventSummary.CreateParticipantForServiceProvider();
            serviceProvider.Participant.Organisation= EventSummary.CreateOrganisation();
            serviceProvider.Participant.Organisation.Name = "Bay Hill Hospital";
            serviceProvider.Participant.Organisation.NameUsage = OrganisationNameUsage.Other;

            serviceProvider.Participant.Organisation.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, "8003620000045562") }; 

            var electronicCommunicationDetail = EventSummary.CreateElectronicCommunicationDetail(
                "0345754566",
                ElectronicCommunicationMedium.Telephone,
                ElectronicCommunicationUsage.WorkPlace);

            serviceProvider.Participant.ElectronicCommunicationDetails = new List<ElectronicCommunicationDetail> { electronicCommunicationDetail, electronicCommunicationDetail };

            var address = EventSummary.CreateAddress();
            address.AddressPurpose = AddressPurpose.Residential;
            address.AustralianAddress = EventSummary.CreateAustralianAddress();
            address.AustralianAddress.UnstructuredAddressLines = new List<string> { "1 Clinician Street" };
            address.AustralianAddress.SuburbTownLocality = "Nehtaville";
            address.AustralianAddress.State = AustralianState.QLD;
            address.AustralianAddress.PostCode = "5555";
            address.AustralianAddress.DeliveryPointId = 32568931;

            if (!mandatorySectionsOnly)
            {
              serviceProvider.Role = BaseCDAModel.CreateRole(Occupation.GeneralMedicalPractitioner);
            }
            else
            {
              serviceProvider.Role = BaseCDAModel.CreateRole(NullFlavour.Other);
            }

            serviceProvider.Participant.Addresses = new List<IAddress> 
            { 
                address, address 
            };

            return serviceProvider;
        }

        /// <summary>
        /// Creates and Hydrates a Service Provider Person
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated IParticipationHealthProfessional object</returns>
        private static IParticipationServiceProvider CreateServiceProviderPerson(Boolean mandatorySectionsOnly)
        {
            var serviceProvider = EventSummary.CreateServiceProvider();

            var participant = EventSummary.CreateParticipantForServiceProvider();
            participant.Person = EventSummary.CreatePersonForServiceProvider();

            var personName = BaseCDAModel.CreatePersonName();
            personName.FamilyName = "Dr Jane Anderson";
            personName.NameUsages = new List<NameUsage> { NameUsage.Legal };
            participant.Person.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPII, "8003610000001145") }; 
            participant.Person.PersonNames = new List<IPersonName> { personName };
            participant.Person.Organisation = BaseCDAModel.CreateEmploymentOrganisation();
            participant.Person.Organisation.Name = "Hay Bill Hospital (ServiceProviderPerson)";
            participant.Person.Organisation.NameUsage = OrganisationNameUsage.Other;
            participant.Person.Organisation.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, "8003620000045562") };
            participant.Person.Organisation.Department = "Some department service provider";
            participant.Person.Organisation.EmploymentType = EventSummary.CreateCodableText("123", CodingSystem.AMT, "ServiceProvider Casual", null, null);
            participant.Person.Organisation.Occupation = Occupation.TyreFitter;
            participant.Person.Organisation.PositionInOrganisation = EventSummary.CreateCodableText("567", CodingSystem.AMT, "ServiceProvider Manager", null, null);            


            participant.ElectronicCommunicationDetails = new List<ElectronicCommunicationDetail> 
            { 
                EventSummary.CreateElectronicCommunicationDetail("0345754566", ElectronicCommunicationMedium.Telephone, ElectronicCommunicationUsage.WorkPlace), 
                EventSummary.CreateElectronicCommunicationDetail("1234", ElectronicCommunicationMedium.Email, ElectronicCommunicationUsage.Home)
            };

            var address = EventSummary.CreateAddress();
            address.AddressPurpose = AddressPurpose.Business;
            address.AustralianAddress = EventSummary.CreateAustralianAddress();
            address.AustralianAddress.UnstructuredAddressLines = new List<string> { "1 Clinician Street" };
            address.AustralianAddress.SuburbTownLocality = "Nehtaville";
            address.AustralianAddress.State = AustralianState.QLD;
            address.AustralianAddress.PostCode = "5555";
            address.AustralianAddress.DeliveryPointId = 32568931;

            if (!mandatorySectionsOnly)
            {
              serviceProvider.Role = BaseCDAModel.CreateRole(Occupation.GeneralMedicalPractitioner);
            } 
              else
            {
              serviceProvider.Role = BaseCDAModel.CreateRole(NullFlavour.NegativeInfinity);
            }

            participant.Addresses = new List<IAddress>
            {
                address, address
            };

            serviceProvider.Participant = participant;

            return serviceProvider;
        }

        /// <summary>
        /// Creates and Hydrates the Diagnoses Intervention section for the Event Summary
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated DiagnosesIntervention object</returns>
        private static DiagnosesIntervention CreateDiagnosesIntervention()
        {
            var diagnosesInterventions = EventSummary.CreateDiagnosesInterventions();

            var medicalHistoryItems = new List<IMedicalHistoryItem>
            {
                CreateMedicalHistoryItem("Medical history comment goes here", "Medical history item goes here"),
                CreateMedicalHistoryItem("Another medical history comment goes here", "Another medical history item goes here")
            };

            var procedureList = new List<Procedure>
            {
                CreateProcedure("Procedure comment goes here.", "397956004", "Hip replacement"),
                CreateProcedure("Another procedure comment.", "397956002", "Leg replacement")
            };

            var diagnosisList = new List<IProblemDiagnosis>
            {
                CreateProblemDiagnosis("Problem/Diagnosis comment goes here.", "116223007", "Comorbidity"),
                CreateProblemDiagnosis("Another Problem/Diagnosis comment goes here.", "116223008", "Dippity")
            };

            diagnosesInterventions.Procedures = procedureList;
            diagnosesInterventions.MedicalHistoryItem = medicalHistoryItems;
            diagnosesInterventions.ProblemDiagnosis = diagnosisList;

            return diagnosesInterventions;
        }

        /// <summary>
        /// Creates a problem diagnosis.
        /// </summary>
        /// <param name="comment">Problem diagnosis comment.</param>
        /// <param name="code">Problem diagnosis code.</param>
        /// <param name="name">Problem diagnosis name.</param>
        /// <returns></returns>
        private static IProblemDiagnosis CreateProblemDiagnosis(string comment, string code, string name)
        {
            var diagnois = EventSummary.CreateProblemDiagnosis();
            diagnois.Comment = comment;
            diagnois.ProblemDiagnosisIdentification = EventSummary.CreateProblemDiagnosisIdentification(code, CodingSystem.SNOMED, name, "");
            diagnois.DateOfResolutionRemission = new ISO8601DateTime(DateTime.Now.AddDays(-49), ISO8601DateTime.Precision.Day);
            diagnois.DateOfOnset = new ISO8601DateTime(DateTime.Now);
            return diagnois;
        }

        /// <summary>
        /// Creates a procedure.
        /// </summary>
        /// <param name="comment">Procedure comemnt.</param>
        /// <param name="code">Procedure code.</param>
        /// <param name="name">Procedure name.</param>
        /// <returns></returns>
        private static Procedure CreateProcedure(string comment, string code, string name)
        {
            var procedure = EventSummary.CreateProcedure();
            procedure.Comment = comment;
            procedure.ProcedureName = EventSummary.CreateProcedureName(code, CodingSystem.SNOMED, name, null, null);
            procedure.Start = new ISO8601DateTime(DateTime.Now.AddDays(-12));
            return procedure;
        }

        /// <summary>
        /// Creates a medication history item.
        /// </summary>
        /// <param name="comment">Medication history item comment.</param>
        /// <param name="description">Medication history item description.</param>
        /// <returns></returns>
        private static IMedicalHistoryItem CreateMedicalHistoryItem(string comment, string description)
        {
            var medicalHistoryItem = EventSummary.CreateMedicalHistoryItem();
            medicalHistoryItem.DateTimeInterval = BaseCDAModel.CreateInterval(
                    new ISO8601DateTime(DateTime.Now, ISO8601DateTime.Precision.Day),
                    new ISO8601DateTime(DateTime.Now.AddDays(200), ISO8601DateTime.Precision.Day));

            medicalHistoryItem.ItemDescription = description;
            medicalHistoryItem.ItemComment = comment;
            return medicalHistoryItem;
        }

        /// <summary>
        /// Creates and Hydrates the adverse substance reactions section for the Event Summary
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated List of IAdverseReactionsEventSummay object</returns>
        private static IAdverseReactionsWithoutExclusions CreateAdverseReactions()
        {
            var reactions = EventSummary.CreateAdverseReactions();

            reactions.AdverseSubstanceReaction = new List<Reaction>
                                                     {
                                                         CreateAdverseReaction("90580008", "Fish"),
                                                         CreateAdverseReaction("90580001", "Peanuts")
                                                     };
            
            return reactions;
        }

        /// <summary>
        /// Creates an adverse reaction.
        /// </summary>
        /// <param name="code">Code for the adverse reaction.</param>
        /// <param name="name">Name of the adverse reaction.</param>
        /// <returns></returns>
        private static Reaction CreateAdverseReaction(string code, string name)
        {
            Reaction reaction = EventSummary.CreateReaction();

            reaction.SubstanceOrAgent = EventSummary.CreateSubstanceOrAgent
                (
                    code,
                    CodingSystem.SNOMED,
                    name,
                    name,
                    null
                );

            reaction.ReactionEvent = EventSummary.CreateReactionEvent();
            reaction.ReactionEvent.Manifestations = new List<ICodableText>
            {
                EventSummary.CreateManifestation
                (
                    "271807003",
                    CodingSystem.SNOMED,
                    "Skin Rash",
                    null,
                    null
                ),
                EventSummary.CreateManifestation
                (
                    "271807001",
                    CodingSystem.SNOMED,
                    "Red Sore",
                    null,
                    null
                )
            };

            return reaction;
        }

        /// <summary>
        /// Creates and hydrates the diagnostic investigations section.
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A hydrated 'DiagnosticInvestigations' object.</returns>
        private static IDiagnosticInvestigations CreateDiagnosticInvestigations(Boolean mandatorySectionsOnly)
        {
            IDiagnosticInvestigations diagnosticInvestigations = EventSummary.CreateDiagnosticInvestigations();

            diagnosticInvestigations.ImagingExaminationResult = new List<IImagingExaminationResult>
                                                                {
                                                                    CreateImagingResults("Leg Image"),
                                                                    CreateImagingResults("Head Image")
                                                                };

            // Pathology test results
            diagnosticInvestigations.PathologyTestResult = new List<PathologyTestResult> 
                                                           {
                                                                CreatePathologyResults("Chemisty studies (set)", PitNameAndPath),
                                                                CreatePathologyResults("Blood studies (set)")
                                                           };

            // Other Test Result 
            diagnosticInvestigations.OtherTestResult = new List<OtherTestResult>
                                                       {
                                                              CreateOtherTestResultAttachment(),
                                                              CreateOtherTestResultText()
                                                       };
      
            // Requested Service
            diagnosticInvestigations.RequestedService = CreateRequestedService(mandatorySectionsOnly);

            return diagnosticInvestigations;
        }

        /// <summary>
        /// Creates and hydrates the 'Other Test Result' Attachment section.
        /// </summary>
        /// <returns>A hydrated 'OtherTestResult' object.</returns>
        private static OtherTestResult CreateOtherTestResultAttachment()
        {
          var otherTestResult = BaseCDAModel.CreateOtherTestResult();
          otherTestResult.ReportName = BaseCDAModel.CreateCodableText(null, null, null, "Report with Attachment", null);
          otherTestResult.ReportStatus = ResultStatus.Interim;

          // Report ExternalData
          ExternalData report = BaseCDAModel.CreateExternalData();
          report.ExternalDataMediaType = MediaType.PDF;
          report.Path = ResultFileNameAndPath;
          report.Caption = "Path File";

          otherTestResult.ReportContent = BaseCDAModel.CreateEncapsulatedData();
          otherTestResult.ReportContent.ExternalData = report;
          otherTestResult.ReportDate = new ISO8601DateTime(DateTime.Now.AddDays(-2));

          return otherTestResult;
        }

        /// <summary>
        /// Creates and hydrates the 'Other Test Result' text section.
        /// </summary>
        /// <returns>A hydrated 'OtherTestResult' object.</returns>
        private static OtherTestResult CreateOtherTestResultText()
        {
          var otherTestResult = BaseCDAModel.CreateOtherTestResult();
          otherTestResult.ReportName = BaseCDAModel.CreateCodableText(null, null, null, "Report with Text", null);
          otherTestResult.ReportStatus = ResultStatus.Interim;

          otherTestResult.ReportContent = BaseCDAModel.CreateEncapsulatedData();
          otherTestResult.ReportContent.Text = "Report Content Text";
          otherTestResult.ReportDate = new ISO8601DateTime(DateTime.Now.AddDays(-2));

          return otherTestResult;
        }

        /// <summary>
        /// Creates and hydrates the 'Imaging Examination Results' section.
        /// </summary>
        /// <param name="name">Name of the imaging examination results.</param>
        /// <returns>A hydrated 'IImagingExaminationResultDischargeSummary' object.</returns>
        private static IImagingExaminationResult CreateImagingResults(string name)
        {
            // Image 1
            ExternalData image1 = EventSummary.CreateExternalData();
            image1.ExternalDataMediaType = MediaType.JPEG;
            image1.Path = ImageFileNameAndPath;
            image1.Caption = "X-Ray";

            // Image 2
            ExternalData image2 = EventSummary.CreateExternalData();
            image2.ExternalDataMediaType = MediaType.JPEG;
            image2.Path = ImageFileNameAndPath;
            image2.Caption = "X-Ray - Left Femur";

            // Image 3
            ExternalData image3 = EventSummary.CreateExternalData();
            image3.ExternalDataMediaType = MediaType.JPEG;
            image3.Path = ImageFileNameAndPath;
            image3.Caption = "X-Ray - Right Arm";

            // Anatomical site 1
            AnatomicalSite anatomicalSite1 = CreateAnatomicalSite(
                "Femur Length",
                "50496004",
                CodingSystem.SNOMED,
                "left Femur",
                "left",
                new List<ExternalData> { image1, image2 }
                );

            // Anatomical site 2
            AnatomicalSite anatomicalSite2 = CreateAnatomicalSite(
                "Arm Length",
                "50496005",
                CodingSystem.SNOMED,
                "right Arm",
                "right",
                new List<ExternalData> { image3 }
                );

            // Imaging results 1
            IImagingResult imagingResult1 = EventSummary.CreateImagingResult();
            imagingResult1.Comments = new List<string> { "Femur measured during ultrasound scan.", "Legs measured during ultrasound scan." };
            imagingResult1.ResultName = EventSummary.CreateResultName("16310003", CodingSystem.SNOMED, "ultrasound scan", null, null);
            imagingResult1.ResultValue = EventSummary.CreateResultValue();
            imagingResult1.ResultValue.ValueAsCodableText = EventSummary.CreateCodableText("765676767", CodingSystem.SNOMED, "ultrasound scan description", null, null);
            imagingResult1.ResultValueStatus = HL7ObservationInterpretationNormality.Normal;
            imagingResult1.ResultValueReferenceRangeDetails = new List<ResultValueReferenceRangeDetail>
                                                                  {
                                                                      CreateReferenceRange("86228006", "normal range", "ml", "17", "13"), 
                                                                      CreateReferenceRange("86228007", "high range", "ml", "50", "100")
                                                                  };

            // Imaging results 2
            IImagingResult imagingResult2 = EventSummary.CreateImagingResult();
            imagingResult2.Comments = new List<string> { "Neck measured during ultrasound scan.", "Neck measured during ultrasound scan." };
            imagingResult2.ResultName = EventSummary.CreateResultName("16310040", CodingSystem.SNOMED, "neck ultrasound scan", null, null);
            imagingResult2.ResultValue = EventSummary.CreateResultValue();
            imagingResult2.ResultValue.ValueAsCodableText = EventSummary.CreateCodableText("77777", CodingSystem.SNOMED, "x-ray description", null, null);
            imagingResult2.ResultValueStatus = HL7ObservationInterpretationNormality.Normal;
            imagingResult2.ResultValueReferenceRangeDetails = new List<ResultValueReferenceRangeDetail>
                                                                  {
                                                                      CreateReferenceRange("86228006", "normal range", "kg", "15", "18"), 
                                                                      CreateReferenceRange("86228007", "high range", "kg", "60", "110")
                                                                  };

            // Imaging results 3
            IImagingResult imagingResult3 = EventSummary.CreateImagingResult();
            imagingResult3.Comments = new List<string> { "Waist measured during ultrasound scan.", "Waist measured during ultrasound scan." };
            imagingResult3.ResultName = EventSummary.CreateResultName("16310042", CodingSystem.SNOMED, "waist ultrasound scan", null, null);
            imagingResult3.ResultValue = EventSummary.CreateResultValue();
            imagingResult3.ResultValue.ValueAsCodableText = EventSummary.CreateCodableText("765676767", CodingSystem.SNOMED, "ultrasound scan description", null, null);
            imagingResult3.ResultValueStatus = HL7ObservationInterpretationNormality.Normal;
            imagingResult3.ResultValueReferenceRangeDetails = new List<ResultValueReferenceRangeDetail>
                                                                  {
                                                                      CreateReferenceRange("86228006", "normal range", "ml", "15", "18"), 
                                                                      CreateReferenceRange("86228007", "high range", "ml", "60", "110")
                                                                  };


            // Image 4
            ExternalData image4 = EventSummary.CreateExternalData();
            image4.ExternalDataMediaType = MediaType.JPEG;
            image4.Path = ImageFileNameAndPath;
            image4.Caption = "4 X-Ray";

            // Image details 1
            IImageDetails imageDetails1 = EventSummary.CreateImageDetails();
            imageDetails1.DateTime = new ISO8601DateTime(DateTime.Now);
            imageDetails1.SubjectPosition = "Supine";
            imageDetails1.SeriesIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.3.1.2.2654654654654564", "Series Identifier");
            imageDetails1.Image = image4;

            // Image 5
            ExternalData image5 = EventSummary.CreateExternalData();
            image5.ExternalDataMediaType = MediaType.JPEG;
            image5.Path = ImageFileNameAndPath;
            image5.Caption = "5 X-Ray";

            // Image details 2
            IImageDetails imageDetails2 = EventSummary.CreateImageDetails();
            imageDetails2.DateTime = new ISO8601DateTime(DateTime.Now);
            imageDetails2.SubjectPosition = "Sublime";
            imageDetails2.SeriesIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.3.1.2.2654654654654564", "Series Identifier");
            imageDetails2.Image = image5; 

            // Image 6
            ExternalData image6 = EventSummary.CreateExternalData();
            image6.ExternalDataMediaType = MediaType.JPEG;
            image6.Path = ImageFileNameAndPath;
            image6.Caption = "6 X-Ray";

            // Image details 3
            IImageDetails imageDetails3 = EventSummary.CreateImageDetails();
            imageDetails3.DateTime = new ISO8601DateTime(DateTime.Now);
            imageDetails3.SubjectPosition = "Head";
            imageDetails3.SeriesIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.3.1.2.2654654654654564", "Series Identifier");
            imageDetails3.Image = image6; 

            // Imaging result group 1
            IImagingResultGroup imagingResultGroup1 = EventSummary.CreateImagingResultGroup();
            imagingResultGroup1.Results = new List<IImagingResult>
                                              {
                                                  imagingResult1 
                                              };
            imagingResultGroup1.AnatomicalSite = anatomicalSite1;
            imagingResultGroup1.ResultGroupName = EventSummary.CreateResultGroupName
                (
                    "268445003",
                    CodingSystem.SNOMED,
                    "ultrasound scan - obstetric",
                    null,
                    null
                );

            // Imaging result group 2
            IImagingResultGroup imagingResultGroup2 = EventSummary.CreateImagingResultGroup();
            imagingResultGroup2.Results = new List<IImagingResult>
                                              {
                                                  imagingResult3
                                              };
            imagingResultGroup2.AnatomicalSite = anatomicalSite2;
            imagingResultGroup2.ResultGroupName = EventSummary.CreateResultGroupName
                (
                    "268445333",
                    CodingSystem.SNOMED,
                    "ultrasound scan - other",
                    null,
                    null
                );

            // Imaging examination result 1
            ImagingExaminationResult imagingExaminationResult = EventSummary.CreateImagingExaminationResult();
            imagingExaminationResult.ClinicalInformationProvided = "Patient pregnant. Confirm dates. Estimate from LNMP 18 weeks.";
            imagingExaminationResult.ExaminationRequestDetails = new List<IImagingExaminationRequest>
                                                                     {
                                                                         CreateImagingExaminationRequest("A/U Obstetric - Dating", imageDetails1),
                                                                         CreateImagingExaminationRequest("A/U Skin - Stuff", new List<IImageDetails> { imageDetails2, imageDetails3 })
                                                                     };
            imagingExaminationResult.ExaminationResultName = EventSummary.CreateExaminationResultName("1234", CodingSystem.METEOR, name, name, null);
            imagingExaminationResult.Findings = "Normal obstetric ultrasound with foetal biometry indicating getational age of 18W0D.";
            imagingExaminationResult.Modality = EventSummary.CreateModality("16310003", CodingSystem.SNOMED, "ultrasound", null, null);
            imagingExaminationResult.ResultDateTime = new ISO8601DateTime(DateTime.Now.AddDays(-2));
            imagingExaminationResult.ExaminationResultStatus = ResultStatus.Final;
            imagingExaminationResult.ExaminationResultRepresentation = "ResultRepresentation";
            imagingExaminationResult.ResultGroup = new List<IImagingResultGroup>
                                                       {
                                                           imagingResultGroup1, imagingResultGroup2
                                                       };

            return imagingExaminationResult;
        }

        private static PathologyTestResult CreatePathologyResults(string name, string simpleNarrativePath)
        {
            // Pathology test result
            var pathologyTestResult = EventSummary.CreatePathologyTestResult();

            if (!simpleNarrativePath.IsNullOrEmptyWhitespace()) pathologyTestResult.xPreNarrative = File.ReadAllText(simpleNarrativePath);

            pathologyTestResult.TestResultDateTime = new ISO8601DateTime(DateTime.Now.AddDays(-2));
            pathologyTestResult.OverallTestResultStatus = ResultStatus.Final;

            var specimenDetail = EventSummary.CreateSpecimenDetail();
            specimenDetail.CollectionDateTime = new ISO8601DateTime(DateTime.Now.AddDays(-2));

            pathologyTestResult.PathologyTestSpecimenDetail = new List<SpecimenDetail> { specimenDetail };

            pathologyTestResult.TestResultName = EventSummary.CreateCodableText("18719-5", CodingSystem.LOINC, name, null, null);

            return pathologyTestResult;
        }


        /// <summary>
        /// Creates and hydrates the 'Pathology Test Results' section.
        /// </summary>
        /// <param name="name">Name of the pathology test result.</param>
        /// <returns>A hydrated 'PathologyTestResult' object.</returns>
        private static PathologyTestResult CreatePathologyResults(string name)
        {
            // Image 1
            ExternalData image1 = EventSummary.CreateExternalData();
            image1.ExternalDataMediaType = MediaType.JPEG;
            image1.Path = ImageFileNameAndPath;
            image1.Caption = "X-Ray";

            // Image 1
            ExternalData image2 = EventSummary.CreateExternalData();
            image2.ExternalDataMediaType = MediaType.JPEG;
            image2.Path = ImageFileNameAndPath;
            image2.Caption = "X-Ray";

            // Report 1
            ExternalData report1 = EventSummary.CreateExternalData();
            report1.ExternalDataMediaType = MediaType.PDF;
            report1.Path = ResultFileNameAndPath;
            report1.Caption = "Results";

           
            // Anatomical site 1
            AnatomicalSite anatomicalSite1 = CreateAnatomicalSite(
                "Femur Length",
                "50496004",
                CodingSystem.SNOMED,
                "left Femur",
                "left",
                new List<ExternalData> { image1 }
                );

            // Anatomical site 2
            AnatomicalSite anatomicalSite2 = CreateAnatomicalSite(
                "Cubital fossa",
                "50496076",
                CodingSystem.SNOMED,
                "right Femur",
                "right",
                null
                );

            // Anatomical site 3
            AnatomicalSite anatomicalSite3 = CreateAnatomicalSite(
                "Rotia vossa",
                "50496080",
                CodingSystem.SNOMED,
                "left Arm",
                "left",
                null
                );

            // Specimen detail 1
            SpecimenDetail specimenDetail1 = EventSummary.CreateSpecimenDetail();
            specimenDetail1.AnatomicalSite = new List<AnatomicalSite>
                                                 {
                                                     anatomicalSite1
                                                 };
            specimenDetail1.CollectionDateTime = new ISO8601DateTime(DateTime.Now.AddDays(-22));
            specimenDetail1.CollectionProcedure = EventSummary.CreateCollectionProcedure("82078001", CodingSystem.SNOMED, "blood draw", null, null);
            specimenDetail1.CollectionSetting = "Ward 1A";
            specimenDetail1.ContainerIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.36.45364", "CNH45218964");
            specimenDetail1.ParentSpecimenIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.36.45364", EventSummary.CreateGuid());
            specimenDetail1.SpecimenDescription = "physicalDetails-Description";
            specimenDetail1.PhysicalDetails = new List<PhysicalDetails> {CreatePhysicalDetails("6", "ml")};
            specimenDetail1.ReceivedDateTime = new ISO8601DateTime(DateTime.Now);
            specimenDetail1.SamplingPreconditions = EventSummary.CreateSamplingPreconditions("16985007", CodingSystem.SNOMED, "fasting", null, null);
            specimenDetail1.SpecimenIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.36.45364", EventSummary.CreateGuid());
     
            specimenDetail1.SpecimenTissueType = EventSummary.CreateSpecimenTissueType("specimenDetail-SpecimenTissueType-someCode", CodingSystem.SNOMED, "DisplayName", null, null);

            // Specimen detail 2
            SpecimenDetail specimenDetail2 = EventSummary.CreateSpecimenDetail();
            specimenDetail2.AnatomicalSite = new List<AnatomicalSite>
                                                 {
                                                     anatomicalSite2, anatomicalSite3
                                                 };
            specimenDetail2.CollectionDateTime = new ISO8601DateTime(DateTime.Now.AddDays(-12));
            specimenDetail2.CollectionProcedure = EventSummary.CreateCollectionProcedure("82078002", CodingSystem.SNOMED, "Urine sample", null, null);
            specimenDetail2.CollectionSetting = "Ward 3B";
            specimenDetail2.ContainerIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.36.45364", "AZH45218964");
            specimenDetail2.ParentSpecimenIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.36.45364", EventSummary.CreateGuid());
            specimenDetail2.SpecimenDescription = "Urine sample";
            specimenDetail2.PhysicalDetails = new List<PhysicalDetails> {CreatePhysicalDetails("20", "kg")};
            specimenDetail2.ReceivedDateTime = new ISO8601DateTime(DateTime.Now);
            specimenDetail2.SamplingPreconditions = EventSummary.CreateSamplingPreconditions("16985007", CodingSystem.SNOMED, "fasting", null, null);
            specimenDetail2.SpecimenIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.36.45364", EventSummary.CreateGuid());

            // Specimen detail 3
            SpecimenDetail specimenDetail3 = EventSummary.CreateSpecimenDetail();
            specimenDetail3.CollectionDateTime = new ISO8601DateTime(DateTime.Now.AddDays(-12));
            specimenDetail3.CollectionProcedure = EventSummary.CreateCollectionProcedure("82078002", CodingSystem.SNOMED, "Urine sample", null, null);
            specimenDetail3.CollectionSetting = "Ward 3B";
            specimenDetail3.ContainerIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.36.45364", "AZH45218964");
            specimenDetail3.ParentSpecimenIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.36.45364", EventSummary.CreateGuid());
            specimenDetail3.SpecimenDescription = "Urine sample";
            specimenDetail3.PhysicalDetails = new List<PhysicalDetails> {CreatePhysicalDetails("20", "kg")};
            specimenDetail3.ReceivedDateTime = new ISO8601DateTime(DateTime.Now);
            specimenDetail3.SamplingPreconditions = EventSummary.CreateSamplingPreconditions("16985007", CodingSystem.SNOMED, "fasting", null, null);
            specimenDetail3.SpecimenIdentifier = BaseCDAModel.CreateInstanceIdentifier("1.2.36.45364", EventSummary.CreateGuid());

            // Test result 1
            ITestResult testResult1 = EventSummary.CreateTestResult();
            testResult1.Comments = new List<string> { "Sodium test result comments",  "More comments", "Another comment" };
            testResult1.ReferenceRangeGuidance = "Reference range guidance comments for Sodium; eg. the quantity should be between the high and low values";
            testResult1.ResultName = EventSummary.CreateResultName("2951-2", CodingSystem.SNOMED, "Sodium", null, null);
            testResult1.ResultStatus = ResultStatus.Interim;
            testResult1.ResultValue = EventSummary.CreateResultValue();
            testResult1.ResultValue.ValueAsQuantity = EventSummary.CreateQuantity();
            testResult1.ResultValue.ValueAsQuantity.Value = "12";
            testResult1.ResultValue.ValueAsQuantity.Units = "ml";
            testResult1.ResultValueStatus = HL7ObservationInterpretationNormality.Normal;
            testResult1.ResultValueReferenceRangeDetails = new List<ResultValueReferenceRangeDetail>
                                                               {
                                                                   CreateReferenceRange("86228007", "high range", "ml", "50", "100"), 
                                                                   CreateReferenceRange("86228008", "low range", "ml", "10", "20"), 
                                                               };

            // Test result 2
            ITestResult testResult2 = EventSummary.CreateTestResult();
            testResult2.Comments = new List<string> { "Blood test result comments", "More comments", "Another comment" };
            testResult2.ReferenceRangeGuidance = "Reference range guidance comments for blood; eg. the quantity should be between the high and low values";
            testResult2.ResultName = EventSummary.CreateResultName("2951-2", CodingSystem.SNOMED, "Blood", null, null);
            testResult2.ResultStatus = ResultStatus.Final;
            testResult2.ResultValue = EventSummary.CreateResultValue();
            testResult2.ResultValue.ValueAsQuantity = EventSummary.CreateQuantity();
            testResult2.ResultValue.ValueAsQuantity.Value = "5";
            testResult2.ResultValue.ValueAsQuantity.Units = "km";
            testResult2.ResultValueStatus = HL7ObservationInterpretationNormality.Normal;
            testResult2.ResultValueReferenceRangeDetails = new List<ResultValueReferenceRangeDetail>
                                                               {
                                                                   CreateReferenceRange("86228007", "high range", "ml", "50", "100"), 
                                                                   CreateReferenceRange("86228008", "low range", "ml", "10", "20"), 
                                                               };

            // Test result 3
            ITestResult testResult3 = EventSummary.CreateTestResult();
            testResult3.Comments = new List<string> { "Heart test result comments", "More comments", "Another comment" };
            testResult3.ReferenceRangeGuidance = "Reference range guidance comments for heart; eg. the quantity should be between the high and low values";
            testResult3.ResultName = EventSummary.CreateResultName("2951-2", CodingSystem.SNOMED, "Blood", null, null);
            testResult3.ResultStatus = ResultStatus.Final;
            testResult3.ResultValue = EventSummary.CreateResultValue();
            testResult3.ResultValue.ValueAsQuantity = EventSummary.CreateQuantity();
            testResult3.ResultValue.ValueAsQuantity.Value = "5";
            testResult3.ResultValue.ValueAsQuantity.Units = "km";
            testResult3.ResultValueStatus = HL7ObservationInterpretationNormality.Normal;
            testResult3.ResultValueReferenceRangeDetails = new List<ResultValueReferenceRangeDetail>
                                                               {
                                                                   CreateReferenceRange("86228007", "high range", "psi", "2", "150"), 
                                                                   CreateReferenceRange("86228008", "low range", "psi", "15", "200"), 
                                                               };


            // Test request 1
            ITestRequest testRequest1 = EventSummary.CreateTestRequest();
            testRequest1.LaboratoryTestResultIdentifier = BaseCDAModel.CreateInstanceIdentifier(BaseCDAModel.CreateGuid(), "Laboratory Test Result Identifier");
            testRequest1.TestsRequested = new List<ICodableText>
                                              {
                                                  EventSummary.CreateTestRequestName("275707000", CodingSystem.SNOMED, "blood serum tests"),
                                                  EventSummary.CreateTestRequestName("275707001", CodingSystem.SNOMED, "blood pressure tests"),
                                              };

            // Test request 2
            ITestRequest testRequest2 = EventSummary.CreateTestRequest();
            testRequest2.LaboratoryTestResultIdentifier = BaseCDAModel.CreateInstanceIdentifier(BaseCDAModel.CreateGuid(), "Laboratory Test Result Identifier");
            testRequest2.TestsRequested = new List<ICodableText>
                                              {
                                                  EventSummary.CreateTestRequestName("275707005", CodingSystem.SNOMED, "heart serum tests"),
                                                  EventSummary.CreateTestRequestName("275707006", CodingSystem.SNOMED, "heart pressure tests"),
                                              };

            // Test result group 1
            ITestResultGroup testResultGroup1 = EventSummary.CreateTestResultGroup();
            testResultGroup1.Results = new List<ITestResult> { testResult1, testResult2 };
            testResultGroup1.ResultGroupSpecimenDetail = specimenDetail1;
            testResultGroup1.ResultGroupName = EventSummary.CreateResultGroupName
                (
                    "18719-5",
                    CodingSystem.LOINC,
                    "Chemistry Studies (Set)",
                    null,
                    null
                );

            // Test result group 2
            ITestResultGroup testResultGroup2 = EventSummary.CreateTestResultGroup();
            testResultGroup2.Results = new List<ITestResult> { testResult3 };
            testResultGroup2.ResultGroupSpecimenDetail = specimenDetail2;
          testResultGroup2.ResultGroupName = EventSummary.CreateResultGroupName(NullFlavour.Other);


            // Pathology test result
            PathologyTestResult pathologyTestResult = EventSummary.CreatePathologyTestResult();
            pathologyTestResult.Comment = "testResultGroup-Comment";
            pathologyTestResult.Conclusion = "testResultGroup-Conclusion";
            pathologyTestResult.TestResultDateTime = new ISO8601DateTime(DateTime.Now.AddDays(-2));
            pathologyTestResult.PathologicalDiagnosis = new List<ICodableText>
                                                            {
                                                                EventSummary.CreatePathologicalDiagnois("17621005", CodingSystem.SNOMED, "normal", null, null),
                                                                EventSummary.CreatePathologicalDiagnois("17621002", CodingSystem.SNOMED, "abnormal", null, null)
                                                            };
            pathologyTestResult.OverallTestResultStatus = ResultStatus.Final;
            pathologyTestResult.ClinicalInformationProvided = "Hepatitus";
            pathologyTestResult.DiagnosticService = DiagnosticServiceSectionID.Chemistry;
            pathologyTestResult.TestRequestDetails = new List<ITestRequest>
                                                         {
                                                             testRequest1, testRequest2
                                                         };
            pathologyTestResult.PathologyTestSpecimenDetail = new List<SpecimenDetail> { specimenDetail3 };
            pathologyTestResult.TestResultName = EventSummary.CreateCodableText("18719-5", CodingSystem.LOINC, name, null, null);
            pathologyTestResult.TestResultRepresentation = report1;
            pathologyTestResult.PathologyTestResultGroup = new List<ITestResultGroup>
                                                               {
                                                                   testResultGroup1, testResultGroup2
                                                               };
            
            return pathologyTestResult;
        }

        /// <summary>
        /// Creates and hydrates an 'anatomicalSite'.
        /// </summary>
        /// <param name="description"></param>
        /// <param name="code"></param>
        /// <param name="codingSystem"></param>
        /// <param name="name"></param>
        /// <param name="side"></param>
        /// <param name="images"></param>
        /// <returns>AnatomicalSite</returns>
        private static AnatomicalSite CreateAnatomicalSite(string description, string code, CodingSystem codingSystem, string name, string side, List<ExternalData> images)
        {
            var anatomicalSite = EventSummary.CreateAnatomicalSite();
            anatomicalSite.Description = description;
            anatomicalSite.AnatomicalLocation = EventSummary.CreateAnatomicalLocation();
            anatomicalSite.AnatomicalLocation.NameOfLocation = EventSummary.CreateAnatomicLocationName(code, codingSystem, name, null);
            anatomicalSite.AnatomicalLocation.Side = EventSummary.CreateAnatomicLocationSide("8006542", CodingSystem.SNOMED, side, null, null);
            anatomicalSite.Images = images;
            return anatomicalSite;
        }

        /// <summary>
        /// Creates and hydrates an 'IImagingExaminationRequest' object.
        /// </summary>
        /// <param name="examinationRequestName">Name of the examination request.</param>
        /// <param name="imageDetails">List of 'ImageDetails'.</param>
        /// <returns>A hydrated 'IImagingExaminationRequest' object.</returns>
        private static IImagingExaminationRequest CreateImagingExaminationRequest(string examinationRequestName, List<IImageDetails> imageDetails)
        {
            var imagingExaminationRequest = EventSummary.CreateImagingExaminationRequest();
            imagingExaminationRequest.ExaminationRequestedName = new List<String>
                                                                     {
                                                                         examinationRequestName, "another name"
                                                                     };
            imagingExaminationRequest.ReportIdentifier = BaseCDAModel.CreateInstanceIdentifier(BaseCDAModel.CreateGuid(), "3355552BHU-23.3");

            if (imageDetails != null && imageDetails.Any())
            {
                int index = 1;
                foreach (IImageDetails imageDetail in imageDetails)
                {
                    imageDetail.ImageViewName = EventSummary.CreateImageViewName(null, null, null, index + " X-Ray - " + examinationRequestName, null);
                    imageDetail.Image.Caption = imageDetail.ImageViewName.OriginalText;
                    index++;
                }

                imagingExaminationRequest.ImageDetails = imageDetails;
            }

            imagingExaminationRequest.StudyIdentifier = BaseCDAModel.CreateInstanceIdentifier(BaseCDAModel.CreateGuid(), "Accession Number Group: 0008  Element: 0050");

            return imagingExaminationRequest;
        }

        /// <summary>
        /// Creates and hydrates a 'IImagingExaminationRequest' object.
        /// </summary>
        /// <param name="examinationRequestName">Name of the examination request.</param>
        /// <param name="imageDetails">Image details.</param>
        /// <returns>A hydrated 'IImagingExaminationRequest' object</returns>
        private static IImagingExaminationRequest CreateImagingExaminationRequest(String examinationRequestName, IImageDetails imageDetails)
        {
            return CreateImagingExaminationRequest(examinationRequestName, new List<IImageDetails> { imageDetails });
        }

        #endregion
    }
}