using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;

namespace Core.Parsers;

public class CsvParserBase : IDisposable
{
    private readonly StreamReader _reader;
    //private readonly MemoryStream _memoryStream;
    protected readonly CsvReader CsvReader;

    protected CsvParserBase(FileSystemInfo csvFile, bool ignoreBlankLines) : this(OpenCsv(csvFile), ignoreBlankLines)
    {
    }

    protected CsvParserBase(StreamReader reader, bool ignoreBlankLines)
    {
        _reader = reader;
        CsvReader = InitCsvReader(_reader, ignoreBlankLines);
    }

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

    //    CsvReader = InitCsvReader(_reader, ignoreBlankLines);
    //}

    private static CsvReader InitCsvReader(TextReader reader, bool ignoreBlankLines)
    {
        var csvConfiguration = new CsvConfiguration(CultureInfo.CurrentCulture)
        {
	        HasHeaderRecord = true,
	        IgnoreBlankLines = ignoreBlankLines,
	        ReadingExceptionOccurred = exception => false,
            MissingFieldFound = null
        };

        var csvReader = new CsvReader(reader, csvConfiguration);
        return csvReader;
    }

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

        return File.OpenText(csvFile.FullName);
    }
    
    public void Dispose()
    {
        _reader.Dispose();
    }
}