using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using MileageTraker.Web.Models;

namespace MileageTraker.Web.Email
{
	public class ServiceReminderEmail
	{
		private readonly string _emailSubject;
		private readonly string _emailBody;
		public User Recipient { get; set; }
		public IList<ServiceReminder> ServiceReminders { get; set; }

		public string Subject
		{
			get
			{
				if (!ServiceReminders.Any())
					return "No upcoming vehicle services currently scheduled";
				var vehicles = ServiceReminders.Select(sr => sr.Vehicle.VehicleId).Distinct().ToList();
				var vehicleDesc = vehicles.Count > 1 ? vehicles.Count.ToString() + " vehicles" : "Vehicle Id " + vehicles.First();
				var subject = string.Format(_emailSubject, vehicleDesc);
				return subject;
			}
		}

		public string Body
		{
			get
			{
				var reminderTexts = GetReminderTexts();
				var body =
					string.Format(_emailBody,
					              Recipient.FullName,
					              Environment.NewLine + Environment.NewLine
					              + string.Join(Environment.NewLine, reminderTexts)
						);

				return body;
			}
		}

		public ServiceReminderEmail(User recipient, IList<ServiceReminder> serviceReminders)
		{
			_emailSubject = ConfigurationManager.AppSettings["ServiceReminderSubject"];
			_emailBody = ConfigurationManager.AppSettings["ServiceReminderBody"];
			Recipient = recipient;
			ServiceReminders = serviceReminders;
		}

		private IEnumerable<string> GetReminderTexts()
		{
			if (!ServiceReminders.Any())
				return new[] {"No upcoming services currently scheduled"};

			return
				from sr in ServiceReminders
				let diff =
					sr.TargetOdometer - (sr.Vehicle.CurrentOdometer.HasValue ? sr.Vehicle.CurrentOdometer.Value : 0)
				orderby diff
				let description =
					!string.IsNullOrEmpty(sr.Description)
						? String.Format(", description is '{0}'", sr.Description)
						: string.Empty
				let assignedTo =
					!string.IsNullOrEmpty(sr.Vehicle.Assigned)
						? String.Format("assigned to {0}", sr.Vehicle.Assigned)
						: "unassigned"
				select
					string.Format("Vehicle with Id {0}, which is {3}, has a reminder for service {1} miles{2}.",
					              sr.Vehicle.VehicleId, diff < 0 ? " overdue " + (-diff).ToString() : " in " + diff.ToString(),
					              description,
					              assignedTo);
		}
	}
}