using System;
using System.Collections.Generic;
using System.Linq;
using ProjectManagementData;

namespace TelerikMvcPrototype.Models
{
	public class InitiativeModel
	{
		private ProjectManagementEntities _entities { get; set; }

		public IEnumerable<Initiative> Initiatives { get; set; }
		public IEnumerable<Deliverable> Deliverables { get; set; }
		public IEnumerable<WeeklyStatus> Status { get; set; }

		public IEnumerable<decimal> IdealBudget { get { return CalculateIdealBudget(Status); } }

		private DateTime _currentWeek;
		public DateTime CurrentWeek
		{
			get
			{
				var ii = (int)DateTime.Today.DayOfWeek;
				_currentWeek = DateTime.Today.AddDays(-ii - 1);
				return this._currentWeek;
			}
			set { this._currentWeek = value; }
		}

		public Initiative CurrentInitiative { get; set; }
		public WeeklyStatus CurrentStatus { get; set; }
		public int TotalDefectCount
		{
			get
			{
				return CurrentStatus == null ? 0 :
					(CurrentStatus.ActiveDefectCount.HasValue ? CurrentStatus.ActiveDefectCount.Value : 0)
					+ (CurrentStatus.ClosedDefectCount.HasValue ? CurrentStatus.ClosedDefectCount.Value : 0)
					+ (CurrentStatus.ResolvedDefectCount.HasValue ? CurrentStatus.ResolvedDefectCount.Value : 0)
					+ (CurrentStatus.OtherDefectCount.HasValue ? CurrentStatus.OtherDefectCount.Value : 0);
			}
		}

		public InitiativeModel()
		{
			_entities = new ProjectManagementEntities();
			Initiatives = _entities.Initiative.OrderBy(i => i.Name).ToList();
			Deliverables = new List<Deliverable>();
			CurrentInitiative = new Initiative { Budget = 0, StartDate = DateTime.Today, EndDate = DateTime.Today.AddMonths(1) };
			CurrentStatus = new WeeklyStatus { WeekOf = DateTime.Today, Cost = 0, ActiveDefectCount = 0, ClosedDefectCount = 0, ResolvedDefectCount = 0, OtherDefectCount = 0 };
		}

		private static IEnumerable<decimal> CalculateIdealBudget(IEnumerable<ProjectManagementData.WeeklyStatus> weeklyStatus)
		{
			if (weeklyStatus == null) return new List<decimal> { 100, 200, 300, 400, 500 };

			var statusArray = weeklyStatus.ToArray();
			var incrementTotal = 0M;

			for (var ii = 0; ii < weeklyStatus.Count() - 1; ii++)
			{
				incrementTotal += statusArray[ii + 1].Cost - statusArray[ii].Cost;
			}

			var value = weeklyStatus.First().Cost;
			var averageIncrement = incrementTotal / (weeklyStatus.Count() - 1);
			var budgetList = new List<decimal> { value };

			for (var ii = 1; ii < weeklyStatus.Count(); ii++)
			{
				value += averageIncrement;
				budgetList.Add(value);
			}

			return budgetList;
		}
	}
}