using System.Configuration;
using System.Net.Mail;
using System.Reflection;
using System.Web.Security;
using MileageTraker.Web.Models;
using NLog;

namespace MileageTraker.Web.Email
{
	/// <summary>
	/// Email Notification
	/// </summary>
	public class EmailNotificationService
	{
		private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

		private readonly string _emaialFromAddress;
		private readonly string _resetPasswordSubject;
		private readonly string _resetPasswordBody;

		private readonly string _initializePasswordSubject;
		private readonly string _initializePasswordBody;

		private readonly SmtpClient _smtpClient;

		/// <summary>
		/// Initializes a new instance of the <see cref="T:System.Object"/> class.
		/// </summary>
		/// <param name="smtpClient">The SMTP client.</param>
		public EmailNotificationService()
		{
			_smtpClient = new SmtpClient();

			_emaialFromAddress = ConfigurationManager.AppSettings["EmailFromAddress"];

			_resetPasswordSubject = ConfigurationManager.AppSettings["ResetPasswordSubject"];
			_resetPasswordBody = ConfigurationManager.AppSettings["ResetPasswordBody"];

			_initializePasswordSubject = ConfigurationManager.AppSettings["InitializePasswordSubject"];
			_initializePasswordBody = ConfigurationManager.AppSettings["InitializetPasswordBody"];
		}

		/// <summary>
		/// Sends the reset password email.
		/// </summary>
		/// <param name="user">To this user.</param>
		/// <param name="url">Reset url</param>
		public void SendResetPassword(User user, string url)
		{
			var body = string.Format(_resetPasswordBody, url, user.Username);
			SendMessage(new MailMessage(_emaialFromAddress, user.Email, _resetPasswordSubject, body));
		}

		public void SendInitializePassword(User user, string url)
		{
			var body = string.Format(_initializePasswordBody, url, user.FullName, user.Username);
			SendMessage(new MailMessage(_emaialFromAddress, user.Email, _initializePasswordSubject, body));
		}

		public void SendServiceReminder(ServiceReminderEmail email)
		{
			SendMessage(new MailMessage(_emaialFromAddress, email.Recipient.Email, email.Subject, email.Body));
		}

		private void SendMessage(MailMessage mailMessage)
		{
			try
			{
				Logger.Debug("Email sending to " + mailMessage.To + ", subject: " + mailMessage.Subject);
				_smtpClient.Send(mailMessage);
			}
			catch (SmtpException ex)
			{
				Logger.Error(ex, "Failed to send mail");
			}
		}
	}
}