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

namespace MileageTraker.Web.Controllers
{
	[Authorize(Roles = "Administrator, Developer")]
	public class VehicleController : ControllerBase
    {
        public ViewResult Index(bool inactive = false)
        {
	        var vehicles =
		        (from v in DataService.GetVehicles().ToList()
		         where inactive == (v.InactiveDate.HasValue && v.InactiveDate.Value < DateTime.Today.AddDays(1))
		         select new VehicleViewModel(v)).ToList();
			
	        var viewModel = new VehicleResultsViewModel(vehicles, inactive);
			return View(viewModel);
        }

		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);
				SetStatusMessage(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);
				SetStatusMessage("Changes saved for vehicle " + vehicle.VehicleId);
				return RedirectToAction("Details", new { id = vehicle.VehicleId });
            }
            return View(vehicle);
        }

		[AllowAnonymous]
		public JsonResult Exists(string vehicleId, string serviceVehicleId)
		{
			var vehicle = 
                vehicleId != null 
                    ? DataService.GetVehicle(vehicleId)
                    : DataService.GetVehicle(serviceVehicleId);
			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));
		}

		[ActionLog]
		public ActionResult SetInactive(string id)
		{
			var vehicle = DataService.GetVehicle(id);
			if (vehicle.InactiveDate.HasValue)
			{
				SetStatusMessage("Vehicle already inactive");
			}
			else
			{
				vehicle.InactiveDate = DateTime.Now;
				DataService.UpdateVehicle(vehicle);
				SetStatusMessage(string.Format("Vehicle set inactive on {0:MM/dd/yyyy}", vehicle.InactiveDate.Value));
			}
			return RedirectToAction("Details", new {id});  
		}

		[ActionLog]
		public ActionResult SetActive(string id)
		{
			var vehicle = DataService.GetVehicle(id);
			if (!vehicle.InactiveDate.HasValue)
			{
				SetStatusMessage("Vehicle is already active");
			}
			else
			{
				vehicle.InactiveDate = null;
				DataService.UpdateVehicle(vehicle);
				SetStatusMessage(string.Format("Vehicle reactivated"));
			}
			return RedirectToAction("Details", new { id });  
		}

		public ViewResult VehicleCostIndex()
		{
			var vehicleCostItemsYears = DataService.GetValidVehicleCostItemsYears();

			return View(vehicleCostItemsYears);
		}

		public ViewResult VehicleCostReport(int fiscalYear)
		{
			var vehicleCostItems = 
				DataService.GetVehicleCostItems(fiscalYear)
				.OrderBy(i => i.TagNumber).ThenBy(i => i.CostType).ToList();

			var vehicleCostReport = new VehicleCostReport {FiscalYear = fiscalYear, CostItems = vehicleCostItems};

			return View(vehicleCostReport);
		}

		[ActionLog]
		public ActionResult ExportVehicleCostReport(int fiscalYear)
		{
			var vehicleCostItems = 
				DataService.GetVehicleCostItems(fiscalYear)
				.OrderBy(i => i.TagNumber).ThenBy(i => i.CostType).ToList();

			var name = string.Format("VehicleCost_{0}", fiscalYear);

			var export = ExcelWriter<VehicleCostItem>.WriteXls(vehicleCostItems, name, name);
			return File(export, "application/ms-excel", name + ".xls");
		}
    }
}