using System.Data.Entity;
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 RiskController : ControllerBase
	{
		private readonly AppDbContext _context;

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

		public ViewResult Index()
		{
			var models = _context.Risks.ProjectTo<RiskViewModel>().ToArray();
			return View(models);
		}

		public JsonResult Add(AddRiskForm form)
		{
			var customer = _context.Customers.Include(x => x.Risks).Single(x => x.Id == form.CustomerId);

			var risk = Mapper.Map<Risk>(form);

			customer.Risks.Add(risk);

			_context.SaveChanges();

			var model = Mapper.Map<CustomerRiskViewModel>(risk);

			return BetterJson(model);
		}
	}
}