using System;
using System.IO;
using CsvHelper;
using CsvHelper.Configuration;
using LeafWeb.Core.Utility;

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

		protected CsvParserBase(FileSystemInfo csvFile)
		{
			_reader = OpenCsv(csvFile);
			CsvReader = InitCsvReader(_reader);
        }

		protected CsvParserBase(byte[] fileContents)
		{
			_memoryStream = new MemoryStream(fileContents);
			_reader = new StreamReader(_memoryStream);

			CsvReader = InitCsvReader(_reader);
        }

        private static CsvReader InitCsvReader(StreamReader reader)
        {
            var csvReader = new CsvReader(reader);
            csvReader.Configuration.HasHeaderRecord = false;
            csvReader.Configuration.IgnoreBlankLines = false;
            csvReader.Configuration.ReadingExceptionOccurred = exception => false;
            return csvReader;
        }

		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.Context.Record;
		}

		public void Dispose()
		{
			_reader.Dispose();
			if (_memoryStream != null)
				_memoryStream.Dispose();
		}
	}
}