/*
 * Copyright 2013 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.Xml;
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 EReferral 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 
    /// EReferral 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 EReferralSample 
    {
        #region Properties

        public static string OutputFolderPath { get; set; }

        public static String OutputFileNameAndPath
        {
            get
            {
                return OutputFolderPath + @"\EReferral.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

        public EReferralSample()
        {
            // Set the Output Folder Path in the Generic Object Reuse Sample
            GenericObjectReuseSample.OutputFolderPath = OutputFolderPath;
        }

        /// <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 PopulatedEReferralSample()
        {
            XmlDocument xmlDoc = null;

            var eReferral = PopulateEReferral(true);

            try
            {
                CDAGenerator.NarrativeGenerator = new CDANarrativeGenerator();

                //Pass the E-Referral model into the GenerateEReferral method 
                xmlDoc = CDAGenerator.GenerateEReferral(eReferral);

                xmlDoc.Save(OutputFileNameAndPath);
            }
            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 PopulateEReferralSample_1A(string fileName)
        {
            XmlDocument xmlDoc = null;

           var document = PopulateEReferral(true);

            document.SCSContent = EReferral.CreateSCSContent();
            document.SCSContent.Referee = CreateReferee(true);

            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.GenerateEReferral(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 only the mandatory Sections / Entries
        /// </summary>
        public XmlDocument MinPopulatedEReferralSample(string fileName)
        {
            XmlDocument xmlDoc = null;

            var eReferral = PopulateEReferral(true);

            try
            {
                CDAGenerator.NarrativeGenerator = new CDANarrativeGenerator();

                //Pass the E-Referral model into the GenerateEReferral method 
                xmlDoc = CDAGenerator.GenerateEReferral(eReferral);

                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 MaxPopulatedEReferralSample(string fileName)
        {
            XmlDocument xmlDoc = null;

            var eReferral = PopulateEReferral(false);

            try
            {
                CDAGenerator.NarrativeGenerator = new CDANarrativeGenerator();

                //Pass the E-Referral model into the GenerateEReferral method 
                xmlDoc = CDAGenerator.GenerateEReferral(eReferral);

                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;
        }

        #region Populate Methods


        /// <summary>
        /// This method populates an eReferral model with either the mandatory sections only, or both 
        /// the mandatory and optional sections
        /// </summary>
        /// <param name="mandatorySectionsOnly">mandatorySectionsOnly</param>
        /// <returns>EReferral</returns>
        internal static EReferral PopulateEReferral(Boolean mandatorySectionsOnly)
        {
            var eReferral = EReferral.CreateEReferral();

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

            // Include Logo
            eReferral.IncludeLogo = true;

            #region Setup and populate the CDA context model

            // Setup and populate the CDA context model
            var cdaContext = EReferral.CreateCDAContext();
            // Document Id
            cdaContext.DocumentId = BaseCDAModel.CreateIdentifier(BaseCDAModel.CreateOid(), null);

            // Set Id  
            cdaContext.SetId = BaseCDAModel.CreateIdentifier(BaseCDAModel.CreateGuid(), null);
            // CDA Context Version
            cdaContext.Version = "1";

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

            // Legal authenticator
            if (!mandatorySectionsOnly)
            {
                cdaContext.LegalAuthenticator = EReferral.CreateLegalAuthenticator();
                GenericObjectReuseSample.HydrateAuthenticator(cdaContext.LegalAuthenticator, mandatorySectionsOnly);
            }

            // Create information recipient
            if (!mandatorySectionsOnly)
            {
                var recipient1 = EReferral.CreateInformationRecipient();
                var recipient2 = EReferral.CreateInformationRecipient();
                GenericObjectReuseSample.HydrateRecipient(recipient1, RecipientType.Primary, mandatorySectionsOnly);
                GenericObjectReuseSample.HydrateRecipient(recipient2, RecipientType.Secondary, mandatorySectionsOnly);
                cdaContext.InformationRecipients = new List<IParticipationInformationRecipient> { recipient1, recipient2 };
            }

            eReferral.CDAContext = cdaContext;
            #endregion

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

            eReferral.SCSContext = EReferral.CreateSCSContext();

            eReferral.SCSContext.Author = EReferral.CreateAuthor();
            GenericObjectReuseSample.HydrateAuthor(eReferral.SCSContext.Author, mandatorySectionsOnly);

            eReferral.SCSContext.SubjectOfCare = EReferral.CreateSubjectOfCare();
            GenericObjectReuseSample.HydrateSubjectofCare(eReferral.SCSContext.SubjectOfCare, mandatorySectionsOnly);

            if (!mandatorySectionsOnly)
            {
              eReferral.SCSContext.PatientNominatedContacts = CreatePatientNominatedContacts(mandatorySectionsOnly);
            }

            #endregion

            #region Setup and populate the SCS Content model
            // Setup and populate the SCS Content model

            eReferral.SCSContent = EReferral.CreateSCSContent();

            // Referral detail
            eReferral.SCSContent.ReferralReason = "Referral reason";

            eReferral.SCSContent.ReferralDateTime = new ISO8601DateTime(DateTime.Now);
            eReferral.SCSContent.ValidityDuration = EReferral.CreateInterval("6", TimeUnitOfMeasure.Month);
            eReferral.SCSContent.Referee = CreateReferee(mandatorySectionsOnly);

            // Medications
            eReferral.SCSContent.Medications = CreateMedications(mandatorySectionsOnly);

            // Medical history
            eReferral.SCSContent.MedicalHistory = CreateMedicalHistory(mandatorySectionsOnly);

            // Adverse reactions
            eReferral.SCSContent.AdverseReactions = CreateAdverseReactions(mandatorySectionsOnly);

            if (!mandatorySectionsOnly)
            {
              eReferral.SCSContent.UsualGP = CreateUsualGPOrganisation(mandatorySectionsOnly);

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

            #endregion

            return eReferral;
        }

        /// <summary>
        /// Creates the patient nominated contacts section.
        /// </summary>
        /// <returns></returns>
        private static IList<IParticipationPatientNominatedContact> CreatePatientNominatedContacts(Boolean mandatorySectionsOnly)
        {
            IParticipationPatientNominatedContact contact1 = CreatePatientNominatedContactPerson(
                "UsualGP", "Person", "8003610000021101", "1 Clinician Street", "0345754566", mandatorySectionsOnly);

            IParticipationPatientNominatedContact contact2 = CreatePatientNominatedContactPerson(
                "John", "Doe", "8003610000021101", "2 Clinician Street", "0345754888", mandatorySectionsOnly);

            IParticipationPatientNominatedContact contact3 = CreatePatientNominatedContactOrganisation(
                "Some Hospital", "Ward 1F", "8003620000021100", "1 Test Street", "0345754811", mandatorySectionsOnly);

            return new[] { contact1, contact2, contact3 };
        }

        private static IParticipationPatientNominatedContact CreatePatientNominatedContactOrganisation(string name, string department, string id, string addressLine, string phone, Boolean mandatorySectionsOnly)
        {
            IParticipationPatientNominatedContact nominatedContact = EReferral.CreateParticipationPatientNominatedContact();

            nominatedContact.Participant = EReferral.CreatePatientNominatedContact();

            IOrganisation organisation = EReferral.CreateOrganisation();
            organisation.Department = department;
            organisation.Name = name;
            organisation.NameUsage = OrganisationNameUsage.EnterpriseName;
            organisation.Identifiers = new List<Identifier>
                                           {
                                               BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, id)
                                           };

            nominatedContact.Participant.Organisation = organisation;

            // Address
            var address = EReferral.CreateAddress();
            address.AddressPurpose = AddressPurpose.Residential;
            address.AustralianAddress = EReferral.CreateAustralianAddress();
            address.AustralianAddress.UnstructuredAddressLines = new List<string> { addressLine };
            address.AustralianAddress.SuburbTownLocality = "Nehtaville";
            address.AustralianAddress.State = AustralianState.QLD;
            address.AustralianAddress.PostCode = "5555";
            address.AustralianAddress.DeliveryPointId = 32568931;

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

            // Communication
            var electronicCommunicationDetail = EReferral.CreateElectronicCommunicationDetail
                (
                   phone,
                   ElectronicCommunicationMedium.Telephone,
                   new List<ElectronicCommunicationUsage> { ElectronicCommunicationUsage.WorkPlace, ElectronicCommunicationUsage.Home }
                );

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

            if (!mandatorySectionsOnly)
            {
                nominatedContact.Role = EReferral.CreateRole(Occupation.GeneralMedicalPractitioner);
            }
            else
            {
                nominatedContact.Role = EReferral.CreateRole(NullFlavour.TemporarilyUnavailable);
            }

            return nominatedContact;
        }


      /// <summary>
      /// Creates a patient nominated contact.
      /// </summary>
      /// <param name="givenName">Given name</param>
      /// <param name="familyName">Family name</param>
      /// <param name="hpii">Hpii</param>
      /// <param name="addressLine">Address line</param>
      /// <param name="phone">Phone</param>
      /// <param name="mandatorySectionsOnly">Populates only mandatory sections only </param>
      /// <returns>IParticipationPatientNominatedContact</returns>
      private static IParticipationPatientNominatedContact CreatePatientNominatedContactPerson(string givenName, string familyName, string hpii, string addressLine, string phone, Boolean mandatorySectionsOnly)
        {
            IParticipationPatientNominatedContact nominatedContact = EReferral.CreateParticipationPatientNominatedContact();

            nominatedContact.Participant = EReferral.CreatePatientNominatedContact();

            // Name
            var personName = EReferral.CreatePersonName();
            personName.GivenNames = new List<string> { givenName };
            personName.FamilyName = familyName;
            personName.Titles = new List<string> { "Doctor" };
            personName.NameUsages = new List<NameUsage> { NameUsage.Legal };

            nominatedContact.Participant.Person = EReferral.CreatePersonPatientNominatedContacts();

            nominatedContact.Participant.Person.PersonNames = new List<IPersonName> { personName };

            // Address
            var address = EReferral.CreateAddress();
            address.AddressPurpose = AddressPurpose.Business;
            address.AustralianAddress = EReferral.CreateAustralianAddress();
            address.AustralianAddress.UnstructuredAddressLines = new List<string> { addressLine };
            address.AustralianAddress.SuburbTownLocality = "Nehtaville";
            address.AustralianAddress.State = AustralianState.QLD;
            address.AustralianAddress.PostCode = "5555";
            address.AustralianAddress.DeliveryPointId = 32568931;

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

            // Communication
            var electronicCommunicationDetail = EReferral.CreateElectronicCommunicationDetail
                (
                   phone,
                   ElectronicCommunicationMedium.Telephone,
                   ElectronicCommunicationUsage.WorkPlace
                );

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

            // Identifiers
            nominatedContact.Participant.Person.Identifiers = new List<Identifier>
                                  {
                                      BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPII, hpii)
                                  };

            if (!mandatorySectionsOnly)
            {
                nominatedContact.Role = EReferral.CreateRole(Occupation.GeneralMedicalPractitioner);
            } else
            {
                nominatedContact.Role = EReferral.CreateRole(NullFlavour.PositiveInfinity);
            }

            return nominatedContact;
        }

        /// <summary>
        /// Creates and Hydrates a UsualGP
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>>A Hydrated UsualGP object</returns>
        private static IParticipationUsualGP CreateUsualGPOrganisation(Boolean mandatorySectionsOnly)
        {
            IParticipationUsualGP usualGP = EReferral.CreateUsualGP();

            var participant = EReferral.CreateParticipantForUsualGP();

            var organisation = EReferral.CreateOrganisation();
            organisation.Name = "Bay hill hospital (UsualGP Organisation)";
            organisation.NameUsage = OrganisationNameUsage.LocallyUsedName;
            organisation.Department = "Department";

            organisation.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, "8003620000020052") };
            participant.Organisation = organisation;

            var address = EReferral.CreateAddress();
            address.AddressPurpose = AddressPurpose.Business;
            address.AustralianAddress = EReferral.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;

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

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

            participant.ElectronicCommunicationDetails = new List<ElectronicCommunicationDetail> { electronicCommunicationDetail };

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

            usualGP.Participant = participant;

            return usualGP;
        }

        /// <summary>
        /// Creates and Hydrates a UsualGP
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>>A Hydrated UsualGP object</returns>
        private static IParticipationUsualGP CreateUsualGPPerson(Boolean mandatorySectionsOnly)
        {
            var usualGP = EReferral.CreateUsualGP();

            var participant = EReferral.CreateParticipantForUsualGP();

            var personName = EReferral.CreatePersonName();
            personName.GivenNames = new List<string> { "UsualGP" };
            personName.FamilyName = "Person";
            personName.Titles = new List<string> { "Doctor" };
            personName.NameUsages = new List<NameUsage> { NameUsage.Legal };

            var person = EReferral.CreatePersonWithOrganisation();
            person.PersonNames = new List<IPersonName>();
            person.PersonNames.Add(personName);
            person.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPII, "8003610000021101") };

            participant.Person = person;

            var organisation = EReferral.CreateEmploymentOrganisation();
            organisation.Name = "Bay hill hospital";
            organisation.NameUsage = OrganisationNameUsage.LocallyUsedName;
            organisation.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, "8003620000020052") };
            participant.Person.Organisation = organisation;

            var address = EReferral.CreateAddress();
            address.AddressPurpose = AddressPurpose.Business;
            address.AustralianAddress = EReferral.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;

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

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

            participant.ElectronicCommunicationDetails = new List<ElectronicCommunicationDetail> { electronicCommunicationDetail };

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

            usualGP.Participant = participant;

            return usualGP;
        }

        /// Creates and Hydrates an natomicalSite
        /// </summary>
        /// <returns>AnatomicalSite</returns>
        private static AnatomicalSite CreateAnatomicalSite(String description, ICodableText nameOfLocation, ICodableText side, List<ExternalData> images)
        {
          var anatomicalSite = EReferral.CreateAnatomicalSite();
          anatomicalSite.Description = description;
          anatomicalSite.AnatomicalLocation = EReferral.CreateAnatomicalLocation();
          anatomicalSite.AnatomicalLocation.NameOfLocation = nameOfLocation;
          anatomicalSite.AnatomicalLocation.Side = side;
          anatomicalSite.Images = images;
          return anatomicalSite;
        }

        /// <summary>
        /// Creates and Hydrates an natomicalSite
        /// </summary>
        /// <returns>AnatomicalSite</returns>
        private static AnatomicalSite CreateAnatomicalSite(String description, String code, CodingSystem codingSystem, String name, String side, List<ExternalData> images)
        {
            var anatomicalSite = EReferral.CreateAnatomicalSite();
            anatomicalSite.Description = description;
            anatomicalSite.AnatomicalLocation = EReferral.CreateAnatomicalLocation();
            anatomicalSite.AnatomicalLocation.NameOfLocation = EReferral.CreateAnatomicLocationName(code, codingSystem, name, null);
            anatomicalSite.AnatomicalLocation.Side = EReferral.CreateAnatomicLocationSide("7771000", CodingSystem.SNOMED, side, null, null);
            anatomicalSite.Images = images;
            return anatomicalSite;
        }

        /// <summary>
        /// Creates and Hydrates a Reference Range
        /// </summary>
        /// <returns>ReferenceRange</returns>
        private static ResultValueReferenceRangeDetail CreateReferenceRange(String code, String name, String units, Double? high, Double? low)
        {
            var resultValueReferenceRangeDetail = EReferral.CreateResultValueReferenceRangeDetail();
            resultValueReferenceRangeDetail.Range = EReferral.CreateQuantityRange();
            resultValueReferenceRangeDetail.Range.High = high;
            resultValueReferenceRangeDetail.Range.Low = low;
            resultValueReferenceRangeDetail.Range.Units = units;
            resultValueReferenceRangeDetail.ResultValueReferenceRangeMeaning = EReferral.CreateResultValueReferenceRangeMeaning
                                                                                (
                                                                                    code,
                                                                                    CodingSystem.SNOMED,
                                                                                    name,
                                                                                    null,
                                                                                    null
                                                                                );

            return resultValueReferenceRangeDetail;
        }

        /// <summary>
        /// Creates and Hydrates a PhysicalDetails object
        /// </summary>
        /// <param name="value">The Quantity</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 the Medications section for the E-Referral.
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated Medications object</returns>
        private static IMedicationsEReferral CreateMedications(bool mandatorySectionsOnly)
        {
            var medications = EReferral.CreateMedications();

            if (!mandatorySectionsOnly)
            {
                var medicationList = new List<IMedicationInstruction>();

                var medication1 = EReferral.CreateMedication();
                medication1.Directions = "As directed by packaging.";

                medication1.Medicine = EReferral.CreateMedicine("23641011000036102", CodingSystem.AMT,"paracetamol 500 mg + codeine phosphate 30 mg tablet", null, null);
                medicationList.Add(medication1);

                var medication2 = EReferral.CreateMedication();
                medication2.DirectionsNullFlavour = NullFlavour.TemporarilyUnavailable;

                medication2.Medicine = EReferral.CreateMedicine("23641011000036102", CodingSystem.AMT,"paracetamol 500 mg + codeine phosphate 30 mg tablet", null, null);
                medicationList.Add(medication2);

                medications.MedicationsList = medicationList;
            } 
            else
            {
                medications.ExclusionStatement = EReferral.CreateExclusionStatement();
                medications.ExclusionStatement.Value = NCTISGlobalStatementValues.NoneKnown;
            }

            return medications;
        }

        /// <summary>
        /// Creates and Hydrates the medical history section for the E-Referral.
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated MedicalHistory object</returns>
        private static IMedicalHistory CreateMedicalHistory(bool mandatorySectionsOnly)
        {
            var medicalHistory = EReferral.CreateMedicalHistory();

            if (!mandatorySectionsOnly)
            {
                var procedureList = new List<Procedure>();

                var procedure = EReferral.CreateProcedure();
                procedure.Comment = "Procedure Comment goes here.";
                procedure.ProcedureName = EReferral.CreateProcedureName("409870009", CodingSystem.SNOMED, "(1-->3)-beta-D-glucan detection", null, null);
                procedure.Start = new ISO8601DateTime(DateTime.Now.AddDays(-12));
                procedureList.Add(procedure);

                var prodcedure2 = EReferral.CreateProcedure();
                prodcedure2.Comment = "Procedure Comment goes here.";
                prodcedure2.ProcedureName = EReferral.CreateProcedureName("121877003", CodingSystem.SNOMED, "2-Hydroxyadipate measurement", null, null);
                prodcedure2.Start = new ISO8601DateTime(DateTime.Now.AddDays(-40));
                procedureList.Add(prodcedure2);

                var medicalHistoryItems = new List<IMedicalHistoryItem>();
                var medicalHistoryItem = EReferral.CreateMedicalHistoryItem();
                medicalHistoryItem.DateTimeInterval = BaseCDAModel.CreateInterval(
                    new ISO8601DateTime(DateTime.Now, ISO8601DateTime.Precision.Day),
                    new ISO8601DateTime(DateTime.Now.AddDays(200), ISO8601DateTime.Precision.Day));
                medicalHistoryItem.ItemDescription = "Medical history item goes here";
                medicalHistoryItem.ItemComment = "Medical history Comment goes here";
                medicalHistoryItems.Add(medicalHistoryItem);

                var diagnosisList = new List<IProblemDiagnosis>();
                var diagnois = EReferral.CreateProblemDiagnosis();
                diagnois.Comment = "Problem/Diagnosis Comment goes here.";
                diagnois.ProblemDiagnosisIdentification = EReferral.CreateProblemDiagnosisIdentification("24786004", CodingSystem.SNOMED, "7p partial monosomy syndrome", null);
                diagnois.DateOfOnset = new ISO8601DateTime(DateTime.Now);
                diagnois.DateOfResolutionRemission = new ISO8601DateTime(DateTime.Now, ISO8601DateTime.Precision.Day);
                diagnosisList.Add(diagnois);

                medicalHistory.MedicalHistoryItems = medicalHistoryItems;
                medicalHistory.Procedures = procedureList;
                medicalHistory.ProblemDiagnosis = diagnosisList;
            } 

            return medicalHistory;
        }

        /// <summary>
        /// Creates and Hydrates the adverse substance reactions section for E-Referral.
        /// 
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated ReviewedAdverseSubstanceReactions object</returns>
        private static IAdverseReactions CreateAdverseReactions(bool mandatorySectionsOnly)
        {
            var adverseReactions = EReferral.CreateAdverseSubstanceReactions();

            if (!mandatorySectionsOnly)
            {
                adverseReactions.AdverseSubstanceReaction = new List<Reaction>
                                                            {
                                                                CreateAdverseReaction("260112007", "Cocklebur pollen"),
                                                                CreateAdverseReaction("256268002", "Plane pollen")
                                                            };
            } else
            {
                adverseReactions.ExclusionStatement = EReferral.CreateExclusionStatement();
                adverseReactions.ExclusionStatement.Value = NCTISGlobalStatementValues.NoneKnown;
            }

            return adverseReactions;
        }

        /// <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 = EReferral.CreateReaction();

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

            reaction.ReactionEvent = EReferral.CreateReactionEvent();
            reaction.ReactionEvent.Manifestations = new List<ICodableText>
            {
                EReferral.CreateManifestation
                (
                    "21909001",
                    CodingSystem.SNOMED,
                    "Fetal viability", // Add the name to make it unique when multiple reactions are created
                    null,
                    null
                ),
                EReferral.CreateManifestation
                (
                    "15296000",
                    CodingSystem.SNOMED,
                    "Sterility", // Add the name to make it unique when multiple reactions are created
                    null,
                    null
                )
            };

            return reaction;
        }


        private static List<RequestedService> CreateRequestedService(Boolean mandatorySectionsOnly)
        {
            var requestedServiceList = new List<RequestedService>();

            // Create Service Provider for a Person
            var requestedServicePerson = EReferral.CreateRequestedService();

            requestedServicePerson.RequestedServiceDescription = EReferral.CreateRequestedServiceDescription("399208008", CodingSystem.SNOMED, "chest x-ray", null, null);
            requestedServicePerson.ServiceBookingStatus = EventTypes.Definition;
            // Create Duration
            requestedServicePerson.SubjectOfCareInstructionDescription = "Subject Of Care Instruction Description";
            requestedServicePerson.RequestedServiceDateTime = new ISO8601DateTime(DateTime.Now.AddDays(4));
            // Create Person
            requestedServicePerson.ServiceProvider = CreateServiceProviderPerson(mandatorySectionsOnly);

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

            // Create Service Provider for a Organisation
            var requestedServiceOrganisation = EReferral.CreateRequestedService();
            requestedServiceOrganisation.RequestedServiceDescription = EReferral.CreateRequestedServiceDescription("399208008", CodingSystem.SNOMED, "chest x-ray", null, null);
            requestedServiceOrganisation.ServiceBookingStatus = EventTypes.Intent;
            requestedServiceOrganisation.ServiceScheduled = new ISO8601DateTime(DateTime.Now);

            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 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 = EReferral.CreateServiceProvider();

            var participant = EReferral.CreateParticipantForServiceProvider();
            serviceProvider.Participant = participant;

            var personName = BaseCDAModel.CreatePersonName();
            personName.FamilyName = "Dr Jane Anderson";
            personName.NameUsages = new List<NameUsage> { NameUsage.Legal };

            participant.Person = EReferral.CreatePersonForServiceProvider();
            participant.Person.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPII, "8003610000001145") };

            participant.Person.Organisation = EReferral.CreateEmploymentOrganisation();
            participant.Person.Organisation.Name = "Bay Hill Hospital (ServiceProviderPerson)";
            participant.Person.Organisation.NameUsage = OrganisationNameUsage.Other;
            participant.Person.Organisation.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, "8003620000045562") }; 

            participant.Person.PersonNames = new List<IPersonName> { personName };

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

            var electronicCommunicationDetail2 = EReferral.CreateElectronicCommunicationDetail(
                "04355754566",
                ElectronicCommunicationMedium.Mobile,
                ElectronicCommunicationUsage.PrimaryHome);

            participant.ElectronicCommunicationDetails = new List<ElectronicCommunicationDetail> { electronicCommunicationDetail, electronicCommunicationDetail2 };

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

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

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

            return serviceProvider;
        }

        /// <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 = EReferral.CreateServiceProvider();

            serviceProvider.Participant = EReferral.CreateParticipantForServiceProvider();

            serviceProvider.Participant.Organisation = EReferral.CreateOrganisation();
            serviceProvider.Participant.Organisation.Name = "Bay Hill Hospital (ServiceProviderOrganisation)";
            serviceProvider.Participant.Organisation.NameUsage = OrganisationNameUsage.Other;
            serviceProvider.Participant.Organisation.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, "8003620000045562") }; 

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

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

            var address = EReferral.CreateAddress();
            address.AddressPurpose = AddressPurpose.Residential;
            address.AustralianAddress = EReferral.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;

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

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


            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 IParticipationReferee CreateReferee(bool mandatorySectionsOnly)
        {
            var referee = EReferral.CreateReferee();

            var participant = EReferral.CreateParticipantForReferee();
            referee.Participant = participant;

            var personName = BaseCDAModel.CreatePersonName();
            personName.FamilyName = "Dr Jane Anderson";
            personName.NameUsages = new List<NameUsage> { NameUsage.Legal };

            participant.Person = EReferral.CreatePersonForServiceProvider();
            participant.Person.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPII, "8003610000001145") };

            participant.Person.Organisation = EReferral.CreateEmploymentOrganisation();
            participant.Person.Organisation.Name = "Bay Hill Hospital (RefereePerson)";
            participant.Person.Organisation.NameUsage = OrganisationNameUsage.Other;
            participant.Person.Organisation.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, "8003620000045562") };

            participant.Person.PersonNames = new List<IPersonName> { personName };

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

            participant.ElectronicCommunicationDetails = new List<ElectronicCommunicationDetail> { electronicCommunicationDetail };

            var address = EReferral.CreateAddress();
            address.AddressPurpose = AddressPurpose.Business;
            address.AustralianAddress = EReferral.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)
            {
               referee.Role = BaseCDAModel.CreateRole(Occupation.GeneralMedicalPractitioner);
            }
              else
            {
               referee.Role = BaseCDAModel.CreateRole(NullFlavour.AskedButUnknown);
            }

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

            return referee;
        }

        /// <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 IParticipationReferee CreateRefereeOrganisation(bool mandatorySectionsOnly)
        {
            var serviceProvider = EReferral.CreateReferee();

            serviceProvider.Participant = EReferral.CreateParticipantForReferee();

            serviceProvider.Participant.Organisation = EReferral.CreateOrganisation();
            serviceProvider.Participant.Organisation.Name = "Bay Hill Hospital (RefereeOrganisation)";
            serviceProvider.Participant.Organisation.NameUsage = OrganisationNameUsage.Other;
            serviceProvider.Participant.Organisation.Identifiers = new List<Identifier> { BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, "8003620000045562") }; 

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

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

            var address = EReferral.CreateAddress();
            address.AddressPurpose = AddressPurpose.Residential;
            address.AustralianAddress = EReferral.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);
            }

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

            return serviceProvider;
        }

        /// <summary>
        /// Creates and Hydrates the diagnostic investigations substance reactions 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 mandatoryOnly)
        {
            IDiagnosticInvestigations diagnosticInvestigations = EReferral.CreateDiagnosticInvestigations();

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

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

            // Requested Service
            diagnosticInvestigations.RequestedService = CreateRequestedService(mandatoryOnly);

            // Other Test Result 
            diagnosticInvestigations.OtherTestResult = new List<OtherTestResult>
                                                       {
                                                              GenericObjectReuseSample.CreateOtherTestResultAttachment(),
                                                              GenericObjectReuseSample.CreateOtherTestResultText()
                                                       };

            return diagnosticInvestigations;
        }
        #endregion

    }
}
