using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BS.Shared.DataContracts;

namespace HPHBersenbrueck.Calculations
{
	public class HPHBCalculations : BS.Shared.Services.Calculations
	{
		
		public override decimal? GetApprovedHoursTotal(SupportConceptCostBearerRelDC relDC, bool useIsCalculationWithFactor)
		{
			if (relDC.ApprovalPeriodList == null || !relDC.GetApprovedDuration().HasValue)
			{
				return null;
			}
			decimal? hoursTotal = relDC.ApprovalPeriodList.Sum(i => this.GetApprovedHoursTotal(i, relDC.CostBearer.CostRatePeriods));
			if (useIsCalculationWithFactor)
				hoursTotal = ApplyIsCalculationWithFactor(relDC, hoursTotal);

			if (hoursTotal.HasValue)
				hoursTotal = Math.Round(hoursTotal.Value, 10, MidpointRounding.AwayFromZero);
			return hoursTotal;
		}

		

		public override decimal? GetApprovedHoursForPeriod(SupportConceptApprovalPeriodDC scap, List<CostRatePeriodDC> costRatePeriods, DateTime? pStart,
			DateTime? pEnd)
		{
			if (scap.ApprovedBETotal.HasValue)
			{
				return scap.ApprovedBETotal;
			}

			if (!pStart.HasValue || !pEnd.HasValue)
			{
				return null;
			}
			int restTageStart = 0;
			int restTageEnd = 0;
			
			DateTime start = pStart.Value.Date;
			DateTime end = pEnd.Value.Date;

			if (start.Day > 1)
			{
				DateTime 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)
			{
				DateTime 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 wochenStunden = GetApprovedHoursPerWeek(scap, costRatePeriods) ?? 0;

			decimal gesamt = wochenStunden * 4.3m * fullMonths;

			if (restTageStart > 0)
			{
				int days = DateTime.DaysInMonth(pStart.Value.Year, pStart.Value.Month);

				gesamt += ((decimal)restTageStart / days) * 4.3m * wochenStunden;

			}
			if (restTageEnd > 0)
			{
				int days = DateTime.DaysInMonth(pEnd.Value.Year, pEnd.Value.Month);

				gesamt += ((decimal)restTageEnd / days) * 4.3m * wochenStunden;

			}
			return gesamt;
		}

		

	}
}
