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.Id).Name("Box ID");
				Map(m => m.ProgramName).Name("Program Name");
				Map(m => m.ProgramSubtype).Name("Program Subtype");
				Map(m => m.Description).Name("Description");
				Map(m => m.ShredReadyDate).Name("Shread Ready Date");
				Map(m => m.AddedDate).Name("Added Date");
				Map(m => m.Memo).Name("Memo");
			}
		}

		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.Id));
					workbook.SaveAs(stream);
				}
			}
		}
	}
}