/// <summary>
        /// Build person entity and all person related entities like: DrugExposures, ConditionOccurrences, ProcedureOccurrences... from raw data sets
        /// </summary>
        public override Attrition Build(ChunkData data, KeyMasterOffsetManager om)
        {
            this.Offset    = om;
            this.ChunkData = data;
            var result = BuildPerson(PersonRecords.ToList());
            var person = result.Key;

            if (person == null)
            {
                return(result.Value);
            }

            if (!ObservationPeriodsRaw.Any(op => op.StartDate < op.EndDate))
            {
                return(Attrition.InvalidObservationTime);
            }

            var observationPeriods =
                BuildObservationPeriods(person.ObservationPeriodGap,
                                        ObservationPeriodsRaw.Where(op => op.StartDate < op.EndDate).ToArray()).ToArray();

            var payerPlanPeriods = BuildPayerPlanPeriods(PayerPlanPeriodsRaw.ToArray(), null).ToArray();
            var cohort           = BuildCohort(CohortRecords.ToArray(), observationPeriods).ToArray();


            var visitOccurrences = new Dictionary <long, VisitOccurrence>();
            var visitIds         = new List <long>();

            // Build and clenaup visit occurrences entities
            foreach (var visitOccurrence in CleanupVisits(
                         BuildVisitOccurrences(VisitOccurrencesRaw.ToArray(), observationPeriods), cohort,
                         observationPeriods))
            {
                visitOccurrences.Add(visitOccurrence.Id, visitOccurrence);
                visitIds.Add(visitOccurrence.Id);
            }

            long?prevVisitId = null;

            foreach (var visitId in visitIds.OrderBy(v => v))
            {
                if (prevVisitId.HasValue)
                {
                    visitOccurrences[visitId].PrecedingVisitOccurrenceId = prevVisitId;
                }

                prevVisitId = visitId;
            }

            var drugExposures = BuildDrugExposures(DrugExposuresRaw.Where(de => de.StartDate < DateTime.Now).ToArray(),
                                                   visitOccurrences, observationPeriods)
                                .ToArray();
            var deviceExposure = BuildDeviceExposure(DeviceExposureRaw.ToArray(), visitOccurrences, observationPeriods)
                                 .ToArray();
            var conditionOccurrences =
                Cleanup(
                    BuildConditionOccurrences(
                        ConditionOccurrencesRaw.Where(co => co.StartDate < DateTime.Now).ToArray(), visitOccurrences,
                        observationPeriods),
                    cohort).ToArray();
            var procedureOccurrences =
                Cleanup(
                    BuildProcedureOccurrences(ProcedureOccurrencesRaw.ToArray(), visitOccurrences, observationPeriods),
                    cohort).ToArray();

            var observations =
                Cleanup(BuildObservations(ObservationsRaw.ToArray(), visitOccurrences, observationPeriods), cohort)
                .ToArray();
            var measurements =
                Cleanup(BuildMeasurement(MeasurementsRaw.ToArray(), visitOccurrences, observationPeriods), cohort)
                .ToArray();

            // set corresponding PlanPeriodIds to drug exposure entities and procedure occurrence entities
            SetPayerPlanPeriodId(payerPlanPeriods, drugExposures, procedureOccurrences,
                                 visitOccurrences.Values.ToArray(), new DeviceExposure[] { });

            // set corresponding ProviderIds
            SetProviderIds(drugExposures);
            SetProviderIds(conditionOccurrences);
            SetProviderIds(procedureOccurrences);
            SetProviderIds(observations);

            var death          = BuildDeath(DeathRecords.ToArray(), visitOccurrences, observationPeriods);
            var drugCosts      = BuildDrugCosts(drugExposures).ToArray();
            var procedureCosts = BuildProcedureCosts(procedureOccurrences).ToArray();

            // push built entities to ChunkBuilder for further save to CDM database
            AddToChunk(person, death,
                       observationPeriods,
                       payerPlanPeriods,
                       drugExposures,
                       CleanupCondition(conditionOccurrences).ToArray(),
                       procedureOccurrences,
                       CleanupObservations(observations, measurements, conditionOccurrences, procedureOccurrences).ToArray(),
                       measurements,
                       visitOccurrences.Values.ToArray(), null, cohort, deviceExposure, new Note[0]);

            var pg = new PregnancyAlgorithm.PregnancyAlgorithm();

            foreach (var r in pg.GetPregnancyEpisodes(Vocabulary, person, observationPeriods,
                                                      ChunkData.ConditionOccurrences.Where(e => e.PersonId == person.PersonId).ToArray(),
                                                      ChunkData.ProcedureOccurrences.Where(e => e.PersonId == person.PersonId).ToArray(),
                                                      ChunkData.Observations.Where(e => e.PersonId == person.PersonId).ToArray(),
                                                      ChunkData.Measurements.Where(e => e.PersonId == person.PersonId).ToArray(),
                                                      ChunkData.DrugExposures.Where(e => e.PersonId == person.PersonId).ToArray()))
            {
                r.Id = KeyMasterOffsetManager.GetKeyOffset(r.PersonId).ConditionEraId;
                ChunkData.ConditionEra.Add(r);
            }

            return(Attrition.None);
        }
        /// <summary>
        /// Build person entity and all person related entities like: DrugExposures, ConditionOccurrences, ProcedureOccurrences... from raw data sets
        /// </summary>
        public override Attrition Build(ChunkData data, KeyMasterOffsetManager om)
        {
            Offset    = om;
            ChunkData = data;
            var result = BuildPerson(PersonRecords.ToList());
            var person = result.Key;

            if (person == null)
            {
                return(result.Value);
            }

            if (!ObservationPeriodsRaw.Any(op => op.StartDate < op.EndDate))
            {
                return(Attrition.InvalidObservationTime);
            }

            var op = ObservationPeriodsRaw.Where(op =>
                                                 op.StartDate < op.EndDate &&
                                                 op.StartDate.Year >= person.YearOfBirth &&
                                                 op.EndDate.Value.Year >= person.YearOfBirth &&
                                                 op.StartDate.Year <= DateTime.Now.Year).ToArray();

            if (op.Length == 0)
            {
                return(Attrition.InvalidObservationTime);
            }

            var observationPeriods =
                BuildObservationPeriods(person.ObservationPeriodGap, op).ToArray();

            var payerPlanPeriods = BuildPayerPlanPeriods(PayerPlanPeriodsRaw.Where(pp =>
                                                                                   pp.StartDate.Year >= person.YearOfBirth &&
                                                                                   pp.EndDate.Value.Year >= person.YearOfBirth &&
                                                                                   pp.StartDate.Year <= DateTime.Now.Year).ToArray(), null).ToArray();

            var visitDetails = new Dictionary <long, VisitDetail>();
            var visitDetIds  = new List <long>();

            foreach (var vd in BuildVisitDetails(null, VisitOccurrencesRaw.Where(vo =>
                                                                                 vo.StartDate.Year >= person.YearOfBirth &&
                                                                                 vo.EndDate.Value.Year >= person.YearOfBirth &&
                                                                                 vo.StartDate.Year <= DateTime.Now.Year &&
                                                                                 vo.EndDate.Value.Year <= DateTime.Now.Year).ToArray(), observationPeriods).ToArray())
            {
                if (person.MonthOfBirth.HasValue && vd.StartDate.Year < person.YearOfBirth.Value &&
                    vd.StartDate.Month < person.MonthOfBirth ||
                    vd.StartDate.Year < person.YearOfBirth.Value)
                {
                    if (vd.StartDate.Year < person.YearOfBirth.Value)
                    {
                        if (DateTime.TryParse(person.AdditionalFields["frd"], out var frd))
                        {
                            vd.StartDate = frd;
                            vd.EndDate   = frd;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }

                if (visitDetails.ContainsKey(vd.Id))
                {
                    continue;
                }

                visitDetails.Add(vd.Id, vd);
                visitDetIds.Add(vd.Id);
            }

            long?prevVisitDetId = null;

            foreach (var visitId in visitDetIds.OrderBy(v => v))
            {
                if (prevVisitDetId.HasValue)
                {
                    visitDetails[visitId].PrecedingVisitDetailId = prevVisitDetId;
                }

                prevVisitDetId = visitId;
            }

            var visitOccurrences = new Dictionary <long, VisitOccurrence>();
            var visitIds         = new List <long>();

            foreach (var byStartDate in visitDetails.Values.GroupBy(v => v.StartDate))
            {
                var vd                = byStartDate.First();
                var providerId        = byStartDate.Min(v => v.ProviderId);
                var careSiteId        = byStartDate.Min(v => v.CareSiteId);
                var sourceValue       = byStartDate.Min(v => v.SourceValue);
                var visitOccurrenceId = byStartDate.Min(v => v.Id);
                var visitOccurrence   = new VisitOccurrence(vd)
                {
                    //Id = Offset.GetKeyOffset(vd.PersonId).VisitOccurrenceId,
                    Id          = visitOccurrenceId,
                    ProviderId  = providerId,
                    CareSiteId  = careSiteId,
                    SourceValue = sourceValue
                };

                foreach (var visitDetail in byStartDate)
                {
                    visitDetail.VisitOccurrenceId = visitOccurrence.Id;
                }

                visitOccurrences.Add(visitOccurrence.Id, visitOccurrence);
                visitIds.Add(visitOccurrence.Id);
            }


            long?prevVisitId = null;

            foreach (var visitId in visitIds.OrderBy(v => v))
            {
                if (prevVisitId.HasValue)
                {
                    visitOccurrences[visitId].PrecedingVisitOccurrenceId = prevVisitId;
                }

                prevVisitId = visitId;
            }

            SetVisitOccurrenceId(ConditionOccurrencesRaw, visitDetails);
            SetVisitOccurrenceId(ProcedureOccurrencesRaw, visitDetails);
            SetVisitOccurrenceId(DrugExposuresRaw, visitDetails);
            SetVisitOccurrenceId(DeviceExposureRaw, visitDetails);
            SetVisitOccurrenceId(ObservationsRaw, visitDetails);
            SetVisitOccurrenceId(MeasurementsRaw, visitDetails);

            var drugExposures        = BuildDrugExposures(DrugExposuresRaw.ToArray(), visitOccurrences, observationPeriods).ToArray();
            var deviceExposure       = BuildDeviceExposure(DeviceExposureRaw.ToArray(), visitOccurrences, observationPeriods).ToArray();
            var conditionOccurrences = BuildConditionOccurrences(ConditionOccurrencesRaw.ToArray(), visitOccurrences, observationPeriods).ToArray();
            var procedureOccurrences = BuildProcedureOccurrences(ProcedureOccurrencesRaw.ToArray(), visitOccurrences, observationPeriods).ToArray();

            var observations = BuildObservations(ObservationsRaw.ToArray(), visitOccurrences, observationPeriods).ToArray();
            var measurements = BuildMeasurement(MeasurementsRaw.ToArray(), visitOccurrences, observationPeriods).ToArray();

            var death = BuildDeath(DeathRecords.ToArray(), visitOccurrences, observationPeriods);


            if (death != null)
            {
                person.TimeOfDeath = death.StartDate;

                if (death.StartDate < observationPeriods.Min(op => op.StartDate))
                {
                    return(Attrition.UnacceptablePatientQuality);
                }

                if (death.StartDate.Year < person.YearOfBirth || death.StartDate.Year > DateTime.Now.Year)
                {
                    death = null;
                }
            }

            // push built entities to ChunkBuilder for further save to CDM database
            AddToChunk(person,
                       death,
                       observationPeriods,
                       payerPlanPeriods,
                       Clean(drugExposures, person).ToArray(),
                       Clean(conditionOccurrences, person).ToArray(),
                       Clean(procedureOccurrences, person).ToArray(),
                       Clean(observations, person).ToArray(),
                       Clean(measurements, person).ToArray(),
                       visitOccurrences.Values.ToArray(),
                       visitDetails.Values.ToArray(), null,
                       Clean(deviceExposure, person).ToArray(), null);

            var pg = new PregnancyAlgorithm();

            foreach (var r in pg.GetPregnancyEpisodes(Vocabulary, person, observationPeriods,
                                                      ChunkData.ConditionOccurrences.Where(e => e.PersonId == person.PersonId).ToArray(),
                                                      ChunkData.ProcedureOccurrences.Where(e => e.PersonId == person.PersonId).ToArray(),
                                                      ChunkData.Observations.Where(e => e.PersonId == person.PersonId).ToArray(),
                                                      ChunkData.Measurements.Where(e => e.PersonId == person.PersonId).ToArray(),
                                                      ChunkData.DrugExposures.Where(e => e.PersonId == person.PersonId).ToArray()))
            {
                r.Id = Offset.GetKeyOffset(r.PersonId).ConditionEraId;
                ChunkData.ConditionEra.Add(r);
            }


            return(Attrition.None);
        }