using System;
using System.Collections.Generic;
using BeWo.Data.Access;
using BeWo.Data.Entities;
using BeWo.Service.DCEntityMapper;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.Extensions;
using BS.Shared.Services;

namespace BeWo.Service.Plugins
{
	public class ServiceRecordStatisticFactory : AbstractIDSpecificDefaultClass<ServiceRecordStatisticFactory>
	{
		public virtual ServiceRecordStatisticsInfoDC GetServiceRecordStatisticInfo(long costBearer2SupportConceptOid, DateTime statisticsDate)
		{
			return null;
			//if (costBearer2SupportConceptOid == 1)
			//{
			//	var dc = new ServiceRecordStatisticsInfoDC();
			//	dc.Header = new string[5];
			//	dc.Header[0] = "Bewilligungszeitraum:";
			//	dc.Header[1] = "Test1:";
			//	dc.Header[2] = "Test2:";
			//	dc.Header[3] = "Test3:";
			//	dc.Header[4] = "Test4:";
			//	dc.ForegroundColor = new string[5];
			//	dc.ForegroundColor[0] = "#FFFF00";
			//	dc.ForegroundColor[1] = "#FF0000";
			//	dc.ForegroundColor[2] = "#FF00FF";
			//	dc.ForegroundColor[3] = "#00FF00";
			//	dc.ForegroundColor[4] = "#0000FF";

			//	dc.PeriodStatisticInfos = new List<ServiceRecordPeriodStatisticsInfoDC>();

			//	var pdc = new ServiceRecordPeriodStatisticsInfoDC();
			//	dc.PeriodStatisticInfos.Add(pdc);
			//	pdc.LeftValues = new string[5];
			//	pdc.LeftValues[0] = "Überschrift blablabla";
			//	pdc.LeftValues[1] = "456";
			//	pdc.LeftValues[2] = "789";
			//	pdc.LeftValues[3] = "093";
			//	pdc.LeftValues[4] = "56352";

			//	pdc.RightValues = new string[5];
			//	pdc.RightValues[0] = "";
			//	pdc.RightValues[1] = "45,36";
			//	pdc.RightValues[2] = "789,00";
			//	pdc.RightValues[3] = "093";
			//	pdc.RightValues[4] = "56352";

			//	pdc.LeftValueColors = new string[5];
			//	pdc.LeftValueColors[0] = "#888800";
			//	pdc.LeftValueColors[1] = "#880000";
			//	pdc.LeftValueColors[2] = "#880088";
			//	pdc.LeftValueColors[3] = "#008800";
			//	pdc.LeftValueColors[4] = "#000088";

			//	pdc.RightValueColors = new string[5];
			//	pdc.RightValueColors[0] = "#888800";
			//	pdc.RightValueColors[1] = "#880000";
			//	pdc.RightValueColors[2] = "#880088";
			//	pdc.RightValueColors[3] = "#008800";
			//	pdc.RightValueColors[4] = "#000088";

			//	pdc = new ServiceRecordPeriodStatisticsInfoDC();
			//	dc.PeriodStatisticInfos.Add(pdc);
			//	pdc.LeftValues = new string[5];
			//	pdc.LeftValues[0] = "xxxx";
			//	pdc.LeftValues[1] = "456";
			//	pdc.LeftValues[2] = "789";
			//	pdc.LeftValues[3] = "093";
			//	pdc.LeftValues[4] = "56352";

			//	pdc.RightValues = new string[5];
			//	pdc.RightValues[0] = "yyyyy";
			//	pdc.RightValues[1] = "45,36";
			//	pdc.RightValues[2] = "789,00";
			//	pdc.RightValues[3] = "093";
			//	pdc.RightValues[4] = "56352";

			//	pdc.LeftValueColors = new string[5];
			//	pdc.LeftValueColors[0] = "#088800";
			//	pdc.LeftValueColors[1] = "#080000";
			//	pdc.LeftValueColors[2] = "#080088";
			//	pdc.LeftValueColors[3] = "#808800";
			//	pdc.LeftValueColors[4] = "#800088";

			//	pdc.RightValueColors = new string[5];
			//	pdc.RightValueColors[0] = "#488800";
			//	pdc.RightValueColors[1] = "#480000";
			//	pdc.RightValueColors[2] = "#480088";
			//	pdc.RightValueColors[3] = "#408800";
			//	pdc.RightValueColors[4] = "#400088";

			//	return dc;
			//}
		}

		public virtual SupportConceptStatisticsDC CreateSupportConceptStatistics(long costBearer2SupportConceptOid, DateTime statisticsDate)
		{
			return CreateSupportConceptStatisticsImpl(costBearer2SupportConceptOid, statisticsDate);
		}

		public virtual SupportConceptStatisticsDC CreateSupportConceptStatisticsImpl(long costBearer2SupportConceptOid, DateTime statisticsDate)
		{
			return CreateSupportConceptStatisticsImpl(costBearer2SupportConceptOid, statisticsDate, null);
		}

		public virtual SupportConceptStatisticsDC CreateSupportConceptStatisticsImpl(long costBearer2SupportConceptOid, DateTime statisticsDate, long? ignoreServiceRecordOid)
		{

			var stats = new SupportConceptStatisticsDC();
            stats.PeriodStatistics = new List<SupportConceptPeriodStatisticsDC>();
            stats.DateOfCreation = statisticsDate;

            var cb2sc = DAOFactory.GenericDAO.LoadByID<CostBearer2SupportConcept>(costBearer2SupportConceptOid);

            var relDc = CreateCb2ScDC(cb2sc);

			var calc = PluginLoader.FindClass<Calculations>(cb2sc.CostBearer.ID) ?? Calculations.GetInstance(cb2sc.CostBearer.ID);


	        stats.StatisticsStartDate = relDc.StartDate ?? DateTime.MinValue;
            stats.StatisticsEndDate = relDc.EndDate ?? DateTime.MaxValue;
            
            var serviceUnit = relDc.CostBearer.CostRatePeriods.GetCostRatePeriodForDate(CostRatePeriodType.MinutesPerServiceUnit, DateTime.Now);
            stats.ServiceUnitName = serviceUnit.UnitName;

	        var minutesApprovedTotal = (calc.GetApprovedHoursTotal(relDc, true) ?? 0m)*60m;
	        stats.MinutesApprovedTotal = minutesApprovedTotal;
            stats.MinutesApprovedPerWeek = (calc.GetApprovedHoursPerWeek(relDc, DateTime.Now) ?? 0m) *
                                                     60m;
			stats.ApprovedMinutesTillNow = calc.GetApprovedHoursTillNow(relDc, statisticsDate) * 60m;


			foreach (var periodDC in relDc.ApprovalPeriodList)
            {
                var periodStats = new SupportConceptPeriodStatisticsDC();
                periodStats.SupportConceptApprovalPeriod = periodDC;
                stats.PeriodStatistics.Add(periodStats);

                periodStats.MinutesApprovedTotal = (calc.GetApprovedHoursForPeriod(relDc, periodDC, relDc.CostBearer.CostRatePeriods, periodDC.StartDate, periodDC.EndDate, true) ?? 0m) * 60m;
                periodStats.MinutesApprovedPerWeek = (calc.GetApprovedHoursPerWeek(relDc, periodDC, relDc.CostBearer.CostRatePeriods, true) ?? 0m) * 60m;
				periodStats.ApprovedMinutesTillNow = calc.GetApprovedHoursTillNow(periodDC, relDc.CostBearer.CostRatePeriods, statisticsDate, relDc.CostBearer.IsCalculatingWithFactor) * 60m;

				if (periodStats.MinutesApprovedPerWeek == 0 && relDc.EndDate.HasValue &&
					relDc.EndDate < DateTime.Now)
				{
					periodStats.MinutesApprovedPerWeek =
						calc.GetApprovedHoursPerWeek(relDc, relDc.EndDate.Value) ?? 0m;
				}

				periodStats.MinutesApprovedPerMonth = GetApprovedMinutesPerMonth(periodStats);

				if (periodDC.StartDate.HasValue && periodDC.EndDate.HasValue)
				{
					DateTime max = statisticsDate < periodDC.EndDate.Value ? statisticsDate : periodDC.EndDate.Value;
					DateTime s = periodDC.StartDate.Value;

					if (s.Day == 1)
					{
						int monthsUntilNow = 0;
						while ((s = s.AddMonths(1)) < max)
						{
							monthsUntilNow++;
						}

						periodStats.SollTotalUntilThisMonth = periodStats.MinutesApprovedPerMonth*monthsUntilNow;
					}
					else
					{
						DateTime nextMonth = s.AddMonths(1);
						nextMonth = new DateTime(nextMonth.Year, nextMonth.Month, 1);

						var monthsUntilNow = nextMonth.Subtract(s).TotalDays / DateTime.DaysInMonth(s.Year, s.Month);
						while ((nextMonth = nextMonth.AddMonths(1)) < max)
						{
							monthsUntilNow++;
						}

						periodStats.SollTotalUntilThisMonth = periodStats.MinutesApprovedPerMonth * (decimal)monthsUntilNow;
						
					}
					
				}

                
            }

            stats.PeriodStatistics.Sort((p1, p2) =>
            {
	            int c = 0;
	            if (p1.SupportConceptApprovalPeriod.StartDate.HasValue && p2.SupportConceptApprovalPeriod.StartDate.HasValue)
	            {
		            c = p1.SupportConceptApprovalPeriod.StartDate.Value.CompareTo(p2.SupportConceptApprovalPeriod.StartDate.Value);
	            }

	            if (c == 0 && p1.SupportConceptApprovalPeriod.ServiceCategory != null && p2.SupportConceptApprovalPeriod.ServiceCategory != null)
                        c =
                            p1.SupportConceptApprovalPeriod.ServiceCategory.Name.CompareTo(
                                p2.SupportConceptApprovalPeriod.ServiceCategory.Name);
                    return c;
                });
            

            var serviceRecords = DAOFactory.SearchDAO.FindServiceRecordsDetailsForLastDays(costBearer2SupportConceptOid, null);

            var serviceRecordsProcessed = new Dictionary<long, bool>();
			if (ignoreServiceRecordOid.HasValue)
			{
				serviceRecordsProcessed.Add(ignoreServiceRecordOid.Value, true);
			}
			
            foreach (var sr in serviceRecords)
            {
                if (!serviceRecordsProcessed.ContainsKey(sr.Oid.Value))
                {
                    decimal minutesProvided = 0;
                    decimal minutesProvidedRounded = 0;
                    decimal minutesProvidedThisWeek = 0;
                    decimal minutesProvidedThisMonth = 0;
	                decimal minutesProvidedUntilLastMonth = 0;

                    bool billable = false;
                    if (sr.ServiceDescription != null && sr.ServiceDescription.ServiceCategory != null)
                    {
                        billable = sr.ServiceDescription.ServiceCategory.IsBillable;
                    }

                    bool outOfPeriod = true;
                    if (cb2sc.StartDate.HasValue && cb2sc.EndDate.HasValue)
                    {
                        outOfPeriod = false;
	                    DateTime end = cb2sc.EndDate.Value;
						if (end < DateTime.MaxValue.Date)
							end = end.AddDays(1);
                        if (sr.Start < cb2sc.StartDate || sr.Start > end)
                        {
                            outOfPeriod = true;
                        }
                    }

					SupportConceptPeriodStatisticsDC periodStats =
						GetPeriodDCFromServiceRecord(stats.PeriodStatistics, sr);

                    if (billable || (periodStats != null && periodStats.SupportConceptApprovalPeriod.ServiceCategory != null))
                    {
                        minutesProvided = (decimal) sr.DurationMinutes;

	                    if (!billable && periodStats.SupportConceptApprovalPeriod.ServiceCategory != null &&
	                        !periodStats.SupportConceptApprovalPeriod.ServiceCategory.IsBillable)
	                    {
		                    minutesProvidedRounded = minutesProvided;
	                    }
	                    else
	                    {
							var srDc = MapToServiceRecordDCForStatistic(sr); 
							minutesProvidedRounded = calc.GetBillableDurationInMinutes(srDc);
	                    }
	                    

                        var firstOfMonthDt = new DateTime(statisticsDate.Year, statisticsDate.Month, 1);
                        DateTime mondayDt = statisticsDate.GetLast(DayOfWeek.Monday).Date;
                        DateTime sundayDt = statisticsDate.GetNext(DayOfWeek.Sunday).Date;

                        if (sr.Start >= mondayDt && sr.Start < mondayDt.AddDays(7))
                        {
                            minutesProvidedThisWeek = minutesProvidedRounded;
                        }
                        if (sr.Start >= firstOfMonthDt && sr.Start < firstOfMonthDt.AddMonths(1))
                        {
							minutesProvidedThisMonth = minutesProvidedRounded;
                        }
						if (sr.Start >= stats.StatisticsStartDate && sr.Start < firstOfMonthDt)
						{
							minutesProvidedUntilLastMonth += minutesProvidedRounded;
						}
						
                    }
					
                    if (outOfPeriod)
                    {
                        stats.MinutesOutOfApprovedPeriod += minutesProvidedRounded;
                    }
                    else
                    {
                        stats.MinutesProvidedTotal += minutesProvided;
                        stats.MinutesProvidedTotalRounded += minutesProvidedRounded;
                        stats.MinutesProvidedThisWeek += minutesProvidedThisWeek;
                        stats.MinutesProvidedThisMonth += minutesProvidedThisMonth;
						stats.IstTotalUntilThisMonth += minutesProvidedUntilLastMonth;
                    }

                    
                    if (periodStats != null)
					{
						if (outOfPeriod)
						{
							periodStats.MinutesOutOfApprovedPeriod += minutesProvidedRounded;
						}
						{
							periodStats.MinutesProvidedTotal += minutesProvided;
							periodStats.MinutesProvidedTotalRounded += minutesProvidedRounded;
							periodStats.MinutesProvidedThisWeek += minutesProvidedThisWeek;
							periodStats.MinutesProvidedThisMonth += minutesProvidedThisMonth;
							periodStats.IstTotalUntilThisMonth += minutesProvidedUntilLastMonth;
						}
					}
                    serviceRecordsProcessed.Add(sr.Oid.Value, true);
                }
            }


            if (relDc.EndDate.HasValue)
            {
                DateTime dt = DateTime.Now.Date;
                if (relDc.StartDate.HasValue && relDc.StartDate > dt)
                {
                    dt = relDc.StartDate.Value;
                }

                TimeSpan ts = relDc.EndDate.Value.Subtract(dt);
                int days = ts.Days + 1;
                if (days > 0)
                {
                    stats.MinutesFreePerWeekAverage = (stats.MinutesApprovedTotal - stats.MinutesProvidedTotalRounded) / (days / 7m);

                    foreach (var ps in stats.PeriodStatistics)
                    {
						if (ps.SupportConceptApprovalPeriod.StartDate.HasValue && ps.SupportConceptApprovalPeriod.EndDate.HasValue)
						{
							//if (dt.InBetween(ps.SupportConceptApprovalPeriod.StartDate.Value, ps.SupportConceptApprovalPeriod.EndDate.Value,
							//                 true))
							//{
								if (ps.SupportConceptApprovalPeriod.IsApprovedBEShifting)
								{
									DateTime dtPeriod = DateTime.Now.Date;
									if (ps.SupportConceptApprovalPeriod.StartDate.HasValue && ps.SupportConceptApprovalPeriod.StartDate > dtPeriod)
									{
										dtPeriod = ps.SupportConceptApprovalPeriod.StartDate.Value;
									}

									TimeSpan tsPeriod = ps.SupportConceptApprovalPeriod.EndDate.Value.Subtract(dtPeriod);
									int daysPeriod = tsPeriod.Days + 1;
									if (daysPeriod < 0)
										daysPeriod = 0;

									if (daysPeriod != 0)
									{
										ps.MinutesFreePerWeek = (ps.MinutesApprovedTotal - ps.MinutesProvidedTotalRounded)/(daysPeriod/7m);
									}
									else
									{
										ps.MinutesFreePerWeek = (ps.MinutesApprovedTotal - ps.MinutesProvidedTotalRounded);
									}
								}
								else
								{
									ps.MinutesFreePerWeek = ps.MinutesApprovedPerWeek - ps.MinutesProvidedThisWeek;
								}
							//}
						}

						decimal freeTotalPeriod = ps.MinutesApprovedTotal - ps.MinutesProvidedTotalRounded;
						if (ps.MinutesFreePerWeek > freeTotalPeriod)
							ps.MinutesFreePerWeek = freeTotalPeriod;
	                    if (ps.MinutesFreePerWeek < 0)
		                    ps.MinutesFreePerWeek = 0;
                    }
                }
            }
	        decimal freeTotal = stats.MinutesApprovedTotal - stats.MinutesProvidedTotalRounded;
			if (stats.MinutesFreePerWeekAverage > freeTotal)
				stats.MinutesFreePerWeekAverage = freeTotal;
			if (stats.MinutesFreePerWeekAverage < 0)
				stats.MinutesFreePerWeekAverage = 0;


			//Berechne bewilligte Stunden pro Monat und Soll
			stats.MinutesApprovedPerMonth = GetApprovedMinutesPerMonth(stats);
			if (relDc.StartDate.HasValue && relDc.EndDate.HasValue)
			{
				DateTime max = statisticsDate < relDc.EndDate.Value ? statisticsDate : relDc.EndDate.Value;

				DateTime s = relDc.StartDate.Value;

				if (s.Day == 1)
				{
					int monthsUntilNow = 0;
					while ((s = s.AddMonths(1)) < max)
					{
						monthsUntilNow++;
					}

					stats.SollTotalUntilThisMonth = stats.MinutesApprovedPerMonth * monthsUntilNow;
				}
				else
				{
					DateTime nextMonth = s.AddMonths(1);
					nextMonth = new DateTime(nextMonth.Year, nextMonth.Month, 1);

					var monthsUntilNow = nextMonth.Subtract(s).TotalDays / DateTime.DaysInMonth(s.Year, s.Month);
					while ((nextMonth = nextMonth.AddMonths(1)) < max)
					{
						monthsUntilNow++;
					}

					stats.SollTotalUntilThisMonth = stats.MinutesApprovedPerMonth * (decimal)monthsUntilNow;
				}
			}

            return stats;
        }
		

		private SupportConceptCostBearerRelDC CreateCb2ScDC(CostBearer2SupportConcept cb2sc)
		{
			var pDataContract = new SupportConceptCostBearerRelDC();

			if (cb2sc.CostBearer.Organisation != null)
			{
				pDataContract.CostBearer =
					MapperFactory.CompactOrganisationDC_Organisation.MapToNewDC(cb2sc.CostBearer.Organisation);
			}

			pDataContract.CostBearer2SupportConceptOid = cb2sc.Oid;
			pDataContract.CostBearer2SupportConceptVersion = cb2sc.Version;
			pDataContract.Notice = cb2sc.Notice;
			pDataContract.Status = cb2sc.Status;
			//pDataContract.SupportConcept =
			//    MapperFactory.CompactSupportConceptDC_SupportConcept.MapToNewDC(pEntity.SupportConcept);

			pDataContract.RequestedStartDate = cb2sc.RequestedStartDate;
			pDataContract.RequestedEndDate = cb2sc.RequestedEndDate;
			pDataContract.ApprovedStartDate = cb2sc.ApprovedStartDate;
			pDataContract.ApprovedEndDate = cb2sc.ApprovedEndDate;
			pDataContract.CustomerReferenceNumber = cb2sc.CustomerReferenceNumber;

			pDataContract.MonthlyPayment = cb2sc.MonthlyPayment;

			//if (cb2sc.CostBearerContactPerson != null)
			//    pDataContract.CostBearerContactPerson =
			//        MapperFactory.CompactPersonDC_Person.MapToNewDC(cb2sc.CostBearerContactPerson);
			pDataContract.ApprovalPeriodList =
				MapperFactory.SupportConceptApprovalPeriodDC_SupportConceptApprovalPeriod.MapToNewDCs(
					cb2sc.ApprovalPeriodList);
			if (pDataContract.ApprovalPeriodList != null)
			{
				foreach (var item in pDataContract.ApprovalPeriodList)
				{
					if (!item.StartDate.HasValue)
					{
						item.StartDate = cb2sc.ApprovedStartDate.HasValue
											 ? cb2sc.ApprovedStartDate
											 : cb2sc.RequestedStartDate;
					}
					if (!item.EndDate.HasValue)
					{
						item.EndDate = cb2sc.ApprovedEndDate.HasValue
										   ? cb2sc.ApprovedEndDate
										   : cb2sc.RequestedEndDate;
					}
				}
			}
			return pDataContract;
		}

		private SupportConceptPeriodStatisticsDC GetPeriodDCFromServiceRecord(List<SupportConceptPeriodStatisticsDC> stats, ServiceRecord sr)
		{

			foreach (var p in stats)
			{
				DateTime start = DateTime.MinValue;
				DateTime end = DateTime.MaxValue;

				if (p.SupportConceptApprovalPeriod.StartDate.HasValue)
					start = p.SupportConceptApprovalPeriod.StartDate.Value;
				if (p.SupportConceptApprovalPeriod.EndDate.HasValue && p.SupportConceptApprovalPeriod.EndDate.Value.Date < end)
					end = p.SupportConceptApprovalPeriod.EndDate.Value.Date.AddDays(1);

				if (sr.Start >= start && sr.End < end)
				{
					if (p.SupportConceptApprovalPeriod.ServiceCategory != null && p.SupportConceptApprovalPeriod.ServiceCategory.ServiceCategoryOid == sr.ServiceDescription.ServiceCategory.Oid)
						return p;

				}
			}
			foreach (var p in stats)
			{
				DateTime start = DateTime.MinValue;
				DateTime end = DateTime.MaxValue;

				if (p.SupportConceptApprovalPeriod.StartDate.HasValue)
					start = p.SupportConceptApprovalPeriod.StartDate.Value;
				if (p.SupportConceptApprovalPeriod.EndDate.HasValue && p.SupportConceptApprovalPeriod.EndDate.Value.Date < end)
					end = p.SupportConceptApprovalPeriod.EndDate.Value.Date.AddDays(1);

				if (sr.Start >= start && sr.End < end)
				{
					if (p.SupportConceptApprovalPeriod.ServiceCategory == null)
						return p;

				}
			}
			return null;
		}

		private ServiceRecordDC MapToServiceRecordDCForStatistic(ServiceRecord pEntity)
		{
			var pDataContract = new ServiceRecordDC();

			pDataContract.ServiceRecordOid = pEntity.Oid;
			pDataContract.ServiceRecordVersion = pEntity.Version;
			pDataContract.Start = pEntity.Start;
			pDataContract.End = pEntity.End;
			pDataContract.Notice = pEntity.Notice;
			pDataContract.ServiceRecordType = pEntity.ServiceRecordType ?? ServiceRecordTypeId.DefaultActivity;
			// ? pEntity.ServiceRecordType.Value
			// : ServiceRecordTypeId.DefaultActivity;

			if (pEntity.ServiceDescription != null)
			{
				pDataContract.ServiceDescription = MapperFactory.ServiceDescriptionDC_ServiceDescription.MapToNewDC(pEntity.ServiceDescription);
			}

			pDataContract.RoundedDuration = pEntity.RoundedDuration;
			pDataContract.InsertedOn = pEntity.InsTs;
			pDataContract.InsUser = pEntity.InsUser;


			pDataContract.GroupEmployeeCount = pEntity.GroupEmployeeCount;
			pDataContract.GroupPersonCount = pEntity.GroupPersonCount;
			pDataContract.GroupRoundedDuration = pEntity.GroupRoundedDuration;
			pDataContract.GroupOid = pEntity.GroupOid;

			return pDataContract;
		}

		protected virtual ServiceRecordPeriodStatisticsInfoDC CreateDefaultServiceRecordPeriodStatisticsInfo(int rows)
		{
			var dc = new ServiceRecordPeriodStatisticsInfoDC
			{
				LeftValues = new string[rows],
				RightValues = new string[rows],
				LeftValueColors = new string[rows],
				RightValueColors = new string[rows]
			};

			for (int i = 0; i < rows; i++)
			{
				dc.LeftValueColors[i] = "#FF2B508B";
				dc.RightValueColors[i] = "#FF2B508B";
			}

			return dc;
		}

		public virtual decimal GetApprovedMinutesPerMonth(SupportConceptPeriodStatisticsDC periodStats)
		{
			return periodStats.MinutesApprovedPerWeek * (365m / 84m);
		}

		public virtual decimal GetApprovedMinutesPerMonth(SupportConceptStatisticsDC stats)
		{
			return stats.MinutesApprovedPerWeek * (365m / 84m);
		}


		protected bool TimeSpanIsEqual(SupportConceptStatisticsDC r)
		{
			if (r.PeriodStatistics != null && r.PeriodStatistics.Count > 1)
			{
				for (int i = 0; i < r.PeriodStatistics.Count - 1; i++)
				{
					var p1 = r.PeriodStatistics[i];

					if (p1.SupportConceptApprovalPeriod.StartDate.HasValue && p1.SupportConceptApprovalPeriod.EndDate.HasValue)
					{
						for (int j = i + 1; j < r.PeriodStatistics.Count; j++)
						{
							var p2 = r.PeriodStatistics[j];
							if (p2.SupportConceptApprovalPeriod.StartDate.HasValue && p2.SupportConceptApprovalPeriod.EndDate.HasValue)
							{
								if ((p1.SupportConceptApprovalPeriod.StartDate.Value.Date != p2.SupportConceptApprovalPeriod.StartDate.Value.Date) ||
									(p1.SupportConceptApprovalPeriod.EndDate.Value.Date != p2.SupportConceptApprovalPeriod.EndDate.Value.Date))
									return false;
							}
						}
					}
				}
			}
			return true;
		}

	}
}
