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 InventoryTypeReportWriter
	{
		private sealed class InventoryTypeViewModelMap : CsvClassMap<InventoryTypeViewModel>
		{
			public InventoryTypeViewModelMap()
			{
				Map(m => m.Identifier).Name("Identifier");
				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.WeightPerCase).Name("Weight per Case");
				Map(m => m.PricePerCase).Name("Price per Case");
			}
		}

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

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