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 JsonResult All()
		{
			var viewModels = _context.InventoryTypes
				.OrderByDescending(x => x.Name)
				.ProjectTo<InventoryTypeViewModel>();

			return BetterJson(viewModels.ToArray());
		}
	}

	public class InventoryController : ControllerBase
	{
		private readonly AppDbContext _context;

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

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

		public JsonResult All()
		{
			var viewModels = _context.Inventories
				.OrderByDescending(x => x.InventoryType.Name)
				.ProjectTo<InventoryViewModel>()
				.ToArray();

			return BetterJson(viewModels);
		}

		public JsonResult Add(InventoryAddForm form)
		{
			var inventory = Mapper.Map<Inventory>(form);
			inventory.InventoryType = _context.InventoryTypes.Find(form.InventoryTypeId);
			_context.Inventories.Add(inventory);
			_context.SaveChanges();

			var model = Mapper.Map<InventoryViewModel>(inventory);
			return BetterJson(model);
		}
	}
}