using System;
using System.Web.Mvc;
using MileageTraker.Web.Attributes;
using MileageTraker.Web.DAL;
using MileageTraker.Web.Models;
using MileageTraker.Web.Utility;
using MileageTraker.Web.ViewModels.Account;

namespace MileageTraker.Web.Controllers
{
	[UserActivity]
	public class ControllerBase : Controller
	{
		protected readonly DataService DataService = new DataService();

		protected override void Dispose(bool disposing)
		{
			DataService.Dispose();
			base.Dispose(disposing);
		}

		protected override void OnException(ExceptionContext filterContext)
		{
			if (filterContext != null && filterContext.Exception != null)
			{
				var controller = filterContext.RouteData.Values["controller"].ToString();
				var action = filterContext.RouteData.Values["action"].ToString();
				var loggerName = string.Format("{0}Controller.{1}", controller, action);

				log4net.LogManager.GetLogger(loggerName).Error(string.Empty, filterContext.Exception);
			}

			base.OnException(filterContext);
		}

		protected string GetCookieValue(string key)
		{
			return
				HttpContext.Request.Cookies[key] != null
					? HttpContext.Request.Cookies[key].Value
					: null;
		}

		protected void SetCookieValue(string key, string value)
		{
			var cookies = HttpContext.Response.Cookies;
			var httpCookie = cookies[key];
			if (httpCookie == null) return;

			httpCookie.Value = value;
			httpCookie.Expires = DateTime.MaxValue;
		}

		protected string LinkForUrlAction(string urlAction)
		{
			return 
				string.Format("{0}://{1}{2}", 
				              Request.Url.Scheme, Request.Url.Authority, urlAction);
		}

		protected string ResetPassword(User user)
		{
			// don't make a new one if they already have an active token
			var passwordResetToken = 
				user.PasswordResetToken ?? Algorithms.GenerateToken();

			var url = LinkForUrlAction(
				Url.Action("NewPassword", "Account",
				           new NewPasswordViewModel
					           {
						           UserId = user.UserId,
						           PasswordResetToken = passwordResetToken
					           }));
			user.PasswordResetToken = passwordResetToken;
			DataService.UpdateUser(user);
			return url;
		}

		protected SelectList GetPurposeTypesSelectList()
		{
			var selectList = new SelectList(DataService.GetPurposeTypes(), "PurposeTypeId", "Purpose");
			return selectList;
		}
	}
}