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

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

		public InventoryTypeController(AppDbContext context, IMapper mapper)
		{
			_context = context;
			_mapper = mapper;
		}

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

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

			return BetterJson(viewModels.ToArray());
		}

		public ActionResult Export()
		{
			var writer = new InventoryTypeReportWriter();

			var viewModels =
				_context.InventoryTypes
				.OrderByDescending(x => x.Name)
				.ProjectTo<InventoryTypeViewModel>(_mapper.ConfigurationProvider)
				.ToArray();

			var excel = writer.Write(viewModels);

			var filename = $"CommodityTypes{DateTime.Today:yyyyMMdd}.xlsx";

			return
				new FileContentResult(excel, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
				{
					FileDownloadName = filename
				};
		}

		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);
		}
	}
}