using System.Collections.Generic;
using System.IO;
using System.Linq;
using ClosedXML.Excel;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Excel;
using InventoryTraker.Web.Models;

namespace InventoryTraker.Web.Utilities
{
	public class InventoryReportWriter
	{
		private sealed class InventoryViewModelMap : CsvClassMap<InventoryViewModel>
		{
			public InventoryViewModelMap()
			{
				Map(m => m.Name).Name("Name of Commodity");
				Map(m => m.UnitsPerCase).Name("Units per Case");
				Map(m => m.ContainerType).Name("Container Type");
				Map(m => m.Quantity).Name("Case Quantity");
				Map(m => m.ExpirationDate).Name("Expiration Date");
				Map(m => m.AddedDate).Name("Added Date");
				Map(m => m.Memo).Name("Memo");
				Map(m => m.WeightPerCase).Name("Weight per Case");
				Map(m => m.PricePerCase).Name("Price per Case");
			}
		}

		public byte[] Write(IEnumerable<InventoryViewModel> items)
		{
			using (var stream = new MemoryStream())
			{
				WriteStream(items, stream);
				return stream.ToArray();
			}
		}

		public void WriteStream(IEnumerable<InventoryViewModel> items, Stream stream)
		{
			using (var workbook = new XLWorkbook(XLEventTracking.Disabled))
			{
				var worksheet = workbook.AddWorksheet("Current Inventory");
				using (var writer = new CsvWriter(new ExcelSerializer(worksheet)))
				{
					writer.Configuration.RegisterClassMap(new InventoryViewModelMap());
					writer.WriteRecords(items.OrderBy(i => i.Name));
					workbook.SaveAs(stream);
				}
			}
		}
	}
}