using System;
using System.Collections.Generic;
using BeWo.Service.DCEntityMapper;
using BeWo.Service.Plugins;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.Extensions;
using BS.Shared.Services;

namespace BeWo.SBBMainzReports.Calculations
{
	public class SBBMainzServiceRecordStatisticFactory : ServiceRecordStatisticFactory
	{

		

		public override decimal GetApprovedMinutesPerMonth(SupportConceptStatisticsDC stats)
		{
			if (stats.PeriodStatistics != null)
			{
				decimal sum = 0;
				foreach (var pstat in stats.PeriodStatistics)
				{
					sum += GetApprovedMinutesPerMonth(pstat);
				}
				return sum;

			}
			return base.GetApprovedMinutesPerMonth(stats);

			//stats.MinutesApprovedPerWeek * (365m / 84m);
		}

		public override decimal GetApprovedMinutesPerMonth(SupportConceptPeriodStatisticsDC periodStats)
		{
			var scap = periodStats.SupportConceptApprovalPeriod;

			if (!scap.StartDate.HasValue || !scap.EndDate.HasValue)
			{
				return 0;
			}
			int restTageStart = 0;
			int restTageEnd = 0;

			DateTime start = scap.StartDate.Value.Date;
			DateTime end = scap.EndDate.Value.Date;
			
			if (start.Day > 1)
			{
				var endMonat = new DateTime(start.Year, start.Month, 1).AddMonths(1).AddDays(-1);

				if (end < endMonat)
				{
					endMonat = end;
				}
				restTageStart = endMonat.Subtract(start).Days + 1;
				start = endMonat.AddDays(1);
			}
			if (end.AddDays(1).Day != 1)
			{
				var startMonat = new DateTime(end.Year, end.Month, 1);

				restTageEnd += end.Subtract(startMonat).Days + 1;
				
				end = startMonat;
			}

			int fullMonths = 0;
			while (start < end)
			{
				fullMonths++;
				start = start.AddMonths(1);
			}

			decimal monthsTotal = fullMonths;
			
			
			if (restTageStart != 0)
			{
				monthsTotal += restTageStart / (decimal) DateTime.DaysInMonth(scap.StartDate.Value.Date.Year, scap.StartDate.Value.Date.Month);

			}
			if (restTageEnd != 0)
			{
				monthsTotal += restTageEnd / (decimal) DateTime.DaysInMonth(scap.EndDate.Value.Date.Year, scap.EndDate.Value.Date.Month);

			}
			return periodStats.MinutesApprovedTotal / monthsTotal;
		}
	}
}
