using System;
using System.IO;
using CsvHelper;
using CsvHelper.Configuration;

namespace LeafWeb.Core.Parsers
{
	public class CsvParserBase : IDisposable
	{
		private readonly StreamReader _reader;
		protected readonly CsvReader CsvReader;

		protected CsvParserBase(FileSystemInfo csvFile)
		{
			_reader = OpenCsv(csvFile);
			var csvConfiguration = new CsvConfiguration { HasHeaderRecord = false, IgnoreBlankLines = false, IgnoreReadingExceptions = true};
			CsvReader = new CsvReader(_reader, csvConfiguration);
		}

		internal static StreamReader OpenCsv(FileSystemInfo csvFile)
		{
			if (!csvFile.Exists)
				throw new FileNotFoundException($"Cannot find file '{csvFile.Name}'");

			return File.OpenText(csvFile.FullName);
		}

		protected string[] GetNextCsvRowValues()
		{
			// get values from row
			if (!CsvReader.Read())
				return null;

			return CsvReader.CurrentRecord;
		}

		public void Dispose()
		{
			_reader.Dispose();
		}
	}
}