using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MileageTraker.Web.DAL;
using MileageTraker.Web.Models;
using NLog;

namespace MileageTraker.Web.Email
{
	public class ServiceReminderEmailService : IDisposable
	{
		private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
		
		protected readonly DataService DataService = new DataService();
		protected readonly EmailNotificationService EmailService = new EmailNotificationService();
		
		public void SendAllNotificationEmails()
		{
			Logger.Info("Starting vehicle service notifications");
			var serviceReminders = DataService.GetUpcomingServiceReminders().ToList();

			Logger.Info("Got " + serviceReminders.Count + " service reminders.");

			SendAdminEmails(serviceReminders);

			SendUserEmails(serviceReminders);
		}

		private void SendAdminEmails(IList<ServiceReminder> serviceReminders)
		{
			var admins =
				(from u in DataService.GetUsers()
				 where u.Roles.Any(r => r.RoleName == "Vehicle Admin")
				 select u).Distinct().ToList();

			var adminEmails =
				from admin in admins
				select new ServiceReminderEmail(admin, serviceReminders);

			foreach (var email in adminEmails)
			{
				EmailService.SendServiceReminder(email);
			}
		}

		private void SendUserEmails(IList<ServiceReminder> serviceReminders)
		{
			// send email to user
			var userEmails =
				from sr in serviceReminders
				group sr by sr.Vehicle.Assigned
				into g
				let driver = DataService.FindUserByFullName(g.Key)
				where driver != null
				let userReminders = g.ToList()
				select new ServiceReminderEmail(driver, userReminders);

			foreach (var email in userEmails)
			{
				EmailService.SendServiceReminder(email);
			}
		}

		public void Dispose()
		{
			DataService.Dispose();
		}
	}
}