using System;
using System.Web.Mvc;
using MileageTraker.Web.Attributes;
using MileageTraker.Web.DAL;
using MileageTraker.Web.Models;
using MileageTraker.Web.ViewModels.Vehicle;

namespace MileageTraker.Web.Controllers
{
	[Authorize(Roles = "Administrator, Developer")]
	public class VehicleController : ControllerBase
    {
        public ViewResult Index()
        {
        	var vehicles = DataService.GetVehicles();
        	return View(vehicles);
        }

		public ViewResult Details(string id)
        {
			var vehicle = DataService.GetVehicle(id);
            return View(vehicle);
        }

		public PartialViewResult DetailsPartial(string id)
		{
			var vehicle = DataService.GetVehicle(id);
			return PartialView(new VehiclePartialDetails(vehicle));
		}

        public ActionResult Create()
        {
            return View();
        } 

        [HttpPost]
		[ActionLog]
		public ActionResult Create(Vehicle vehicle)
        {
            if (ModelState.IsValid)
            {
                DataService.AddVehicle(vehicle);
				TempData["StatusMessage"] = 
					string.Format("Vehicle {0} created", vehicle.VehicleId);
				return RedirectToAction("Index");  
            }

            return View(vehicle);
        }

		public ActionResult Edit(string id)
        {
			var vehicle = DataService.GetVehicle(id);
            return View(vehicle);
        }

        [HttpPost]
		[ActionLog]
		public ActionResult Edit(Vehicle vehicle)
        {
            if (ModelState.IsValid)
            {
				DataService.UpdateVehicle(vehicle);
				TempData["StatusMessage"] = "Changes saved for vehicle " + vehicle.VehicleId;
				return RedirectToAction("Details", new { id = vehicle.VehicleId });
            }
            return View(vehicle);
        }

		[AllowAnonymous]
		public JsonResult Exists(string vehicleId)
		{
			var vehicle = DataService.GetVehicle(vehicleId);
			return Json(vehicle != null, JsonRequestBehavior.AllowGet);
		}

		[ActionLog]
		public FileResult Export()
		{
			var vehicles = DataService.GetVehicles();
			var export = VehicleImporter.Export(vehicles);
			return File(export, "application/ms-excel", string.Format("ETHRAVehicles{0:yyyy-MM-dd}.xls", DateTime.Today));
		}
    }
}