using System.Configuration;
using System.Net.Mail;
using System.Reflection;
using MileageTraker.Web.Models;
using log4net;

namespace MileageTraker.Web.Email
{
	/// <summary>
	/// Email Notification
	/// </summary>
	public class EmailNotificationService
	{
		private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

		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));
		}

		private void SendMessage(MailMessage mailMessage)
		{
			try
			{
				_smtpClient.Send(mailMessage);
			}
			catch (SmtpException ex)
			{
				Logger.Error("Failed to send mail", ex);
			}
		}
	}
}