public void AddExaminationToPatient(int patientId, Examination exam, ExaminationType examType, IExaminationType examData, WorkFlow workFlow)
        {
            var patient = GetPatient(patientId, true);

            patient.Examinations.Add(exam);
            exam.WorkFlow = workFlow;
            _context.SaveChanges();
            if (examType == ExaminationType.BloodPressure)
            {
                BloodPressureData ExanData = examData as BloodPressureData;
                _context.BloodPressureData.Add(examData as BloodPressureData);
                ExanData.ExaminationId = exam.Id;
                _context.SaveChanges();
            }
            if (examType == ExaminationType.BloodSpO2)
            {
                SpOData ExanData = examData as SpOData;
                _context.SpOData.Add(examData as SpOData);
                ExanData.ExaminationId = exam.Id;
                _context.SaveChanges();
            }
            if (examType == ExaminationType.BodyTemperature)
            {
                BodyTemperatureData ExanData = examData as BodyTemperatureData;
                ExanData.ExaminationId = exam.Id;
                _context.BodyTemperatureData.Add(examData as BodyTemperatureData);
                ExanData.ExaminationId = exam.Id;
                _context.SaveChanges();
            }
        }
        /// <summary>
        ///  Sort and save to DB HL7 incoming Messages.
        /// </summary>
        /// <param name="request"></param>
        void HadleHL7Message(HL7RequestInfo request, string createdFromHl7Message)
        {
            try
            {
                // Handle ADT_A01 - incoming patient registration. Also save the raw HL7 Messages. To log and store it.
                if (request.Message.ToString().Contains("ADT_A01"))
                {
                    var pateitnToAdd = new Entities.Patient()
                    {
                        Archived   = true,
                        Name       = ((NHapi.Model.V23.Message.ADT_A01)request.Message).PID.PatientName.GivenName.Value + " " + ((NHapi.Model.V23.Message.ADT_A01)request.Message).PID.PatientName.FamilyName.Value,
                        Gender     = ((NHapi.Model.V23.Message.ADT_A01)request.Message).PID.Sex.Value,
                        ExternalId = Convert.ToInt32(((NHapi.Model.V23.Message.ADT_A01)request.Message).PID.PatientAccountNumber.ID.Value),
                        Age        = ((NHapi.Model.V23.Message.ADT_A01)request.Message).PID.DateOfBirth.TimeOfAnEvent.Year,
                        BirthDate  = new DateTime(
                            ((NHapi.Model.V23.Message.ADT_A01)request.Message).PID.DateOfBirth.TimeOfAnEvent.Year,
                            ((NHapi.Model.V23.Message.ADT_A01)request.Message).PID.DateOfBirth.TimeOfAnEvent.Month,
                            ((NHapi.Model.V23.Message.ADT_A01)request.Message).PID.DateOfBirth.TimeOfAnEvent.Day),
                        OriginalHL7Message = createdFromHl7Message,
                    };

                    _patientInfoRepository.AddPatient(pateitnToAdd);
                    _patientInfoRepository.Save();
                }
                // Handle  ORU_R01 - incoming Examination data.
                if (request.Message.ToString().Contains("ORU_R01"))
                {
                    int                 externalID        = Convert.ToInt32(((NHapi.Model.V23.Message.ORU_R01)request.Message).GetRESPONSE().PATIENT.PID.PatientAccountNumber.ID.Value);
                    Patient             patient           = new Patient();
                    Examination         examToAdd         = new Examination();
                    BloodPressureData   newExamData       = new BloodPressureData();
                    SpOData             newExaamSPo       = new SpOData();
                    BodyTemperatureData newExamBTD        = new BodyTemperatureData();
                    bool                BloodPressureFalg = false;
                    if (_patientInfoRepository.PatientExistsByExtId(externalID))
                    {
                        patient = _patientInfoRepository.GetPatientByExtID(externalID);
                    }
                    else
                    {
                        // Todo Save Patient.
                    }

                    int obsCount = ((NHapi.Model.V23.Message.ORU_R01)request.Message).GetRESPONSE().ORDER_OBSERVATIONRepetitionsUsed;
                    for (int i = 0; i < obsCount; i++)
                    {
                        var orderObservation = ((NHapi.Model.V23.Message.ORU_R01)request.Message).GetRESPONSE().GetORDER_OBSERVATION(i);
                        int obxCount         = ((NHapi.Model.V23.Message.ORU_R01)request.Message).GetRESPONSE().GetORDER_OBSERVATION(i).OBSERVATIONRepetitionsUsed;
                        for (int j = 0; j < obxCount; j++)
                        {
                            NHapi.Model.V23.Segment.OBX obx = orderObservation.GetOBSERVATION(j).OBX;
                            var obxVaries = orderObservation.GetOBSERVATION(j).OBX.GetObservationValue();

                            if (obx.ObservationIdentifier.Text.Value == "Body temperature")
                            {
                                Examination examToAddBDT = new Examination();
                                examToAddBDT.Description     = String.Empty;
                                examToAddBDT.Archived        = true;
                                examToAddBDT.PatientId       = patient.Id;
                                examToAddBDT.Value           = DateTime.Now.ToString();
                                examToAddBDT.ExaminationType = "Body temperature";
                                newExamBTD.TemperatureValue  = Convert.ToInt32(((NHapi.Base.Model.AbstractPrimitive)obx.GetObservationValue(0).Data).Value);
                                _patientInfoRepository.AddExaminationToPatient(patient.Id, examToAddBDT, ExaminationType.BodyTemperature, newExamBTD, null);
                            }
                            if (obx.ObservationIdentifier.Text.Value == "SpO2")
                            {
                                Examination examToAddSPO = new Examination();
                                examToAddSPO.PatientId       = patient.Id;
                                examToAddSPO.Description     = String.Empty;
                                examToAddSPO.Archived        = true;
                                examToAddSPO.Value           = DateTime.Now.ToString();
                                examToAddSPO.ExaminationType = "SpO2";
                                newExaamSPo.SPOValue         = Convert.ToInt32(((NHapi.Base.Model.AbstractPrimitive)obx.GetObservationValue(0).Data).Value);
                                _patientInfoRepository.AddExaminationToPatient(patient.Id, examToAddSPO, ExaminationType.BloodSpO2, newExaamSPo, null);
                            }
                            if (obx.ObservationIdentifier.Text.Value == "Mean blood pressure")
                            {
                                BloodPressureFalg             = true;
                                examToAdd.PatientId           = patient.Id;
                                examToAdd.Description         = String.Empty;
                                examToAdd.Archived            = true;
                                examToAdd.Value               = DateTime.Now.ToString();
                                examToAdd.ExaminationType     = "BloodPressure";
                                newExamData.MeanBloodPressure = Convert.ToInt32(((NHapi.Base.Model.AbstractPrimitive)obx.GetObservationValue(0).Data).Value);
                            }
                            if (obx.ObservationIdentifier.Text.Value == "Pulse rate")
                            {
                                BloodPressureFalg         = true;
                                examToAdd.PatientId       = patient.Id;
                                examToAdd.Archived        = true;
                                examToAdd.Description     = String.Empty;
                                examToAdd.Value           = DateTime.Now.ToString();
                                examToAdd.ExaminationType = "BloodPressure";
                                newExamData.PulseRate     = Convert.ToInt32(((NHapi.Base.Model.AbstractPrimitive)obx.GetObservationValue(0).Data).Value);
                            }
                            if (obx.ObservationIdentifier.Text.Value == "Diastolic blood pressure")
                            {
                                BloodPressureFalg          = true;
                                examToAdd.PatientId        = patient.Id;
                                examToAdd.Archived         = true;
                                examToAdd.Description      = String.Empty;
                                examToAdd.Value            = DateTime.Now.ToString();
                                examToAdd.ExaminationType  = "BloodPressure";
                                newExamData.DiastolicValue = Convert.ToInt32(((NHapi.Base.Model.AbstractPrimitive)obx.GetObservationValue(0).Data).Value);
                            }
                            if (obx.ObservationIdentifier.Text.Value == "Systolic blood pressure")
                            {
                                BloodPressureFalg         = true;
                                examToAdd.PatientId       = patient.Id;
                                examToAdd.Archived        = true;
                                examToAdd.Description     = String.Empty;
                                examToAdd.Value           = DateTime.Now.ToString();
                                examToAdd.ExaminationType = "BloodPressure";
                                newExamData.SystolicValue = Convert.ToInt32(((NHapi.Base.Model.AbstractPrimitive)obx.GetObservationValue(0).Data).Value);
                            }
                        }
                        if (BloodPressureFalg)
                        {
                            _patientInfoRepository.AddExaminationToPatient(patient.Id, examToAdd, ExaminationType.BloodPressure, newExamData, null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogInformation("HadleHL7Message error: " + ex.Message);
            }
        }
        public IActionResult CreateExamination(int patientId, [FromBody] ExaminationCreationDTO examinationDTO, int workFlowID)
        {
            if (examinationDTO == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!_patientInfoRepository.PatientExists(patientId))
            {
                return(NotFound());
            }
            WorkFlow workFlow = _patientInfoRepository.GetWorkFlow(workFlowID);

            if (examinationDTO.Description == "Body temperature")
            {
                try
                {
                    Examination examToAddBDT = new Examination();
                    examToAddBDT.Description     = String.Empty;
                    examToAddBDT.Archived        = false;
                    examToAddBDT.PatientId       = patientId;
                    examToAddBDT.Value           = DateTime.Now.ToString();
                    examToAddBDT.ExaminationType = "Body temperature";
                    BodyTemperatureData newExamBTD = new BodyTemperatureData()
                    {
                        TemperatureValue = examinationDTO.TemperatureValue.Value
                    };
                    _patientInfoRepository.AddExaminationToPatient(patientId, examToAddBDT, ExaminationType.BodyTemperature, newExamBTD, workFlow);
                    return(Ok());
                }
                catch (Exception ex)
                {
                    _logger.LogCritical("CreateExamination() Error: " + ex.Message.ToString());
                    return(StatusCode(500, "Internal Server Error"));
                }
            }

            if (examinationDTO.Description == "Blood Pressure")
            {
                try
                {
                    Examination examToAddBDT = new Examination();
                    examToAddBDT.Description     = String.Empty;
                    examToAddBDT.Archived        = false;
                    examToAddBDT.PatientId       = patientId;
                    examToAddBDT.Value           = DateTime.Now.ToString();
                    examToAddBDT.ExaminationType = "BloodPressure";
                    BloodPressureData newExamBTD = new BloodPressureData()
                    {
                        SystolicValue     = examinationDTO.SystolicValue.Value,
                        DiastolicValue    = examinationDTO.DiastolicValue.Value,
                        PulseRate         = examinationDTO.PulseRate.Value,
                        MeanBloodPressure = examinationDTO.MeanBloodPressure.Value
                    };

                    _patientInfoRepository.AddExaminationToPatient(patientId, examToAddBDT, ExaminationType.BloodPressure, newExamBTD, workFlow);
                    return(Ok());
                }
                catch (Exception ex)
                {
                    _logger.LogCritical("CreateExamination() Error: " + ex.Message.ToString());
                    return(StatusCode(500, "Internal Server Error"));
                }
            }

            if (examinationDTO.Description == "SpO2")
            {
                try
                {
                    Examination examToAddBDT = new Examination();
                    examToAddBDT.Description     = String.Empty;
                    examToAddBDT.Archived        = false;
                    examToAddBDT.PatientId       = patientId;
                    examToAddBDT.Value           = DateTime.Now.ToString();
                    examToAddBDT.ExaminationType = "SpO2";
                    SpOData newExamBTD = new SpOData()
                    {
                        SPOValue = examinationDTO.SPOValue.Value
                    };

                    _patientInfoRepository.AddExaminationToPatient(patientId, examToAddBDT, ExaminationType.BloodSpO2, newExamBTD, workFlow);
                    return(Ok());
                }
                catch (Exception ex)
                {
                    _logger.LogCritical("CreateExamination() Error: " + ex.Message.ToString());
                    return(StatusCode(500, "Internal Server Error"));
                }
            }

            return(NotFound());
        }