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

namespace MileageTraker.Web.Controllers
{
	[Authorize]
	public class CityController : ControllerBase
	{
		public JsonResult Autocomplete(string term)
		{
			var cities = DataService.GetCitiesAutocomplete(term);
			return Json(cities, JsonRequestBehavior.AllowGet);
		}

		public JsonResult CityNameExists(string cityname)
		{
			var city = DataService.FindCityByName(cityname);
			return Json(city != null, JsonRequestBehavior.AllowGet);
		}

		[Authorize(Roles = "Administrator, Developer")]
		public ActionResult Index()
		{
			var cities = DataService.GetCities().ToList();
			var t = cities.Select(c => Tuple.Create(c.County, c.Name));
			var groupTuple = CustomExtensions.GroupTuple(t);
			return View(groupTuple);
		}

		[Authorize(Roles = "Administrator, Developer")]
		public ActionResult Create(string county)
		{
			var city = new City {County = county};
			return View(city);
		}

		[Authorize(Roles = "Administrator, Developer")]
		[ActionLog]
		[HttpPost]
		public ActionResult Create([Bind(Exclude = "CityId")] City city)
		{
			if (ModelState.IsValid)
			{
				DataService.AddCity(city);

				TempData["StatusMessage"] = "City " + city.Name + " created";
				return RedirectToAction("Index");
			}

			return View(city);
		}

		[Authorize(Roles = "Administrator, Developer")]
		public JsonResult CityNameAvailable(string name)
		{
			var city = DataService.FindCityByName(name);
			return Json(city == null, JsonRequestBehavior.AllowGet);
		}
	}
}
