using System.Linq;
using System.Web.Mvc;
using MileageTraker.Web.Models;

namespace MileageTraker.Web.Controllers
{
	[Authorize(Roles = "Administrator, Developer")]
	public class PurposeController : ControllerBase
	{
		public ActionResult Index()
		{
			return View(DataService.GetPurposeTypes().ToList());
		}

		public ActionResult Details(int id = 0)
		{
			var purposetype = DataService.FindPurposeType(id);
			if (purposetype == null)
			{
				TempData["StatusMessage"] = "Purpose " + id + " not found";
				return RedirectToAction("Index");
			}
			return View(purposetype);
		}

		public ActionResult Create()
		{
			var purposeType = new PurposeType();
			purposeType.SortOrder = DataService.GetPurposeTypes().Max(pt => pt.SortOrder) + 2;
			return View(purposeType);
		}

		[HttpPost]
		public ActionResult Create([Bind(Exclude = "PurposeTypeId")]PurposeType purposetype)
		{
			if (ModelState.IsValid)
			{
				DataService.AddPurposeType(purposetype);

				TempData["StatusMessage"] = "Purpose " + purposetype.Purpose + " created";
				return RedirectToAction("Index");
			}

			return View(purposetype);
		}

		public ActionResult Edit(int id = 0)
		{
			var purposeType = DataService.FindPurposeType(id);
			if (purposeType == null)
			{
				TempData["StatusMessage"] = "Purpose " + id + " not found";
				return RedirectToAction("Index");
			}
			return View(purposeType);
		}

		[HttpPost]
		public ActionResult Edit(PurposeType purposeType)
		{
			if (ModelState.IsValid)
			{
				DataService.UpdatePurposeType(purposeType);

				TempData["StatusMessage"] = "Changes to Purpose  " + purposeType.Purpose + " saved";
				return RedirectToAction("Index");
			}
			return View(purposeType);
		}
	}
}