using System;
using System.Linq;
using System.Web.Mvc;
using InventoryTraker.Web.Services;
using InventoryTraker.Web.Utilities;

namespace InventoryTraker.Web.Controllers
{
	public class ReportController : ControllerBase
	{
		private readonly ReportService _reportService;
		private readonly DistributionReportWriter _distributionReportWriter;
		private readonly MovementReportWriter _movementReportWriter;

		public ReportController(
			ReportService reportService, 
			DistributionReportWriter distributionReportWriter,
			MovementReportWriter movementReportWriter)
		{
			_reportService = reportService;
			_distributionReportWriter = distributionReportWriter;
			_movementReportWriter = movementReportWriter;
		}

		[HttpGet]
		public ActionResult Distribution()
		{
			return View();
		}

		public ActionResult Distribution(DateTime startDate, DateTime endDate)
		{
			var report = _reportService.GetDistributionReport(startDate, endDate);

			return BetterJson(report.ToArray());
		}

		public ActionResult DistributionExcel(DateTime startDate, DateTime endDate)
		{
			var report = _reportService.GetDistributionReport(startDate, endDate);

			var excel = _distributionReportWriter.Write(report);

			var filename = $"InventoryDistributionReport{startDate:yyyyMMdd}-{endDate:yyyyMMdd}.xlsx";

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

		[HttpGet]
		public ActionResult Movement()
		{
			return View();
		}

		public ActionResult Movement(DateTime month)
		{
			var report = _reportService.GetMovementReport(month);

			return BetterJson(report);
		}

		public ActionResult MovementExcel(DateTime month)
		{
			var report = _reportService.GetMovementReport(month);

			var excel = _movementReportWriter.Write(report);

			var filename = $"MonthlyInventoryReport{report.Month:MMMMyyyy}.xlsx";

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