using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using CsvHelper.Configuration;
using CsvHelper.TypeConversion;
using InventoryTraker.Web.Models;

namespace InventoryTraker.Web.Utilities
{
	public class InventoryParser
	{
		private readonly FileSystemInfo _excelFile;

		// ReSharper disable once ClassNeverInstantiated.Local
		private sealed class InventoryAddFormMap : CsvClassMap<InventoryAddForm>
		{
			public InventoryAddFormMap()
			{
				Map(m => m.Id).Name("Box ID").TypeConverter<StringNullConverter>();
				Map(m => m.ProgramName).Name("Program Name").TypeConverter<StringNullConverter>();
				Map(m => m.ProgramSubtype).Name("Program Subtype").TypeConverter<StringNullConverter>();
				Map(m => m.Description).TypeConverter<StringNullConverter>();
				Map(m => m.ShredReadyDate).Name("Shread Ready Date");
				Map(m => m.AddedDate).Name("Added Date");
				Map(m => m.Memo).TypeConverter<StringNullConverter>();
			}
		}

		private class StringNullConverter : StringConverter
		{
			public override object ConvertFromString(TypeConverterOptions options, string text)
			{
				if (string.IsNullOrEmpty(text)) return null;
				if (text.StartsWith("\"") && text.EndsWith("\""))
					return base.ConvertFromString(options, Regex.Replace(text, @"^\""(.*)\""$", "$1"));
				return base.ConvertFromString(options, text);
			}
		}


		public InventoryParser(FileSystemInfo excelFile)
		{
			_excelFile = excelFile;
		}

		public IList<InventoryAddForm> Parse()
		{
			var csvConfiguration = 
				new CsvConfiguration
				{
					IsHeaderCaseSensitive = false,
					IgnoreReadingExceptions = false,
					TrimFields = true,
					SkipEmptyRecords = true,
					ShouldSkipRecord = strings => strings.Take(7).All(string.IsNullOrEmpty)
				};
			csvConfiguration.RegisterClassMap<InventoryAddFormMap>();
			using (var reader = ExcelParserBase.OpenExcel(_excelFile, csvConfiguration))
			{
				return reader.GetRecords<InventoryAddForm>().ToList();
			}
		}
	}
}