using System.IO;
using System.Linq;
using ExcelLibrary.SpreadSheet;
using MileageTraker.Web.Models;
using MileageTraker.Web.Utility;
using MileageTraker.Web.ViewModels;
using MileageTraker.Web.ViewModels.Log;

namespace MileageTraker.Web.DAL
{
	public static class LogImportTemplateWriter
	{
		public static byte[] Write()
		{
			var example =
				new ImportLogViewModel
					{
						CityName = "City Name",
						Date = "10/20/2010",
						EndOdometer = "10010",
						GasPurchased = "3.141",
						LogType = "Commuting",
						Notes = "Template",
						Purpose = "Training",
						VehicleId = "1000"
					};
			const string headerFormat = "[Blue]";

			var worksheet = new Worksheet("LogImport");

			ExcelWriter<ImportLogViewModel>.WriteColumnHeaders(worksheet, formatString: headerFormat);
			ExcelWriter<ImportLogViewModel>.WriteItems(worksheet, new[] { example }, 1); // write the example item

			var propertyCount = ExcelWriter<ImportLogViewModel>.GetPropertyCount();

			worksheet.Cells[0, propertyCount + 1] = new Cell("Accepted values for fields:", headerFormat);

			// purposes
			var dataService = new DataService();
			var puposes =
				from pt in dataService.GetPurposeTypes()
				orderby pt.SortOrder ascending 
				select pt.Purpose;
			worksheet.Cells[1, propertyCount + 2] = new Cell("Purpose", headerFormat);
			ExcelWriter<string>.WriteItems(worksheet, puposes, 2, propertyCount + 2);

			// log types
			var logTypes =
				from i in (new MileageLogType()).GetSelectListItems()
				select i.Text;
			worksheet.Cells[1, propertyCount + 1] = new Cell("Type", headerFormat);
			ExcelWriter<string>.WriteItems(worksheet, logTypes, 2, propertyCount + 1);

			ExcelWriter<ImportLogViewModel>.PadWorksheet(worksheet);

			// save it
			var workbook = new Workbook();
			workbook.Worksheets.Add(worksheet);
			using (var stream = new MemoryStream())
			{
				workbook.Save(stream);
				return stream.ToArray();
			}
		}
	}
}