using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using InventoryTraker.Web.Core;
using InventoryTraker.Web.Data;
using InventoryTraker.Web.Models;

namespace InventoryTraker.Web.Controllers
{
	public class InventoryTypeController : ControllerBase
	{
		private readonly AppDbContext _context;

		public InventoryTypeController(AppDbContext context)
		{
			_context = context;
		}

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

		public JsonResult All()
		{
			var viewModels = _context.InventoryTypes
				.OrderByDescending(x => x.Name)
				.ProjectTo<InventoryTypeViewModel>();

			return BetterJson(viewModels.ToArray());
		}

		public JsonResult Add(InventoryTypeViewModel form)
		{
			if (!ModelState.IsValid)
				return GetModelStateErrorListJson();

			var inventoryType = Mapper.Map<InventoryType>(form);
			_context.InventoryTypes.Add(inventoryType);
			_context.SaveChanges();

			var model = Mapper.Map<InventoryTypeViewModel>(inventoryType);
			return BetterJson(model);
		}

		public JsonResult Update(InventoryTypeViewModel form)
		{
			if (!ModelState.IsValid)
				return GetModelStateErrorListJson();

			var inventoryType = _context.InventoryTypes.Find(form.Id);
			Mapper.Map(form, inventoryType);

			_context.SaveChanges();

			var model = Mapper.Map<InventoryTypeViewModel>(inventoryType);
			return BetterJson(model);
		}
	}
}