using System.Globalization;
using CsvHelper;

namespace Inspectron.Statistics;

public class CsvStatistics
{
    private readonly string _filePath;
    private readonly StreamWriter _stream;
    private readonly FileStream _fileStream;
    private readonly CsvWriter _csv;

    public CsvStatistics(string filePath, string[] headers)
    {
        _filePath = filePath;
        var newFile = !File.Exists(filePath);
        _fileStream = File.Open(_filePath, FileMode.Append);
        _stream = new StreamWriter(_fileStream);
        _csv = new CsvWriter(_stream,CultureInfo.InvariantCulture);
        if (newFile)
        {
            foreach (var header in headers)
            {
                _csv.WriteField(header);
            }
            _csv.NextRecord();
            _csv.Flush();
        }
    }

    public void WriteLine(string[] values)
    {
        for (int i = 0; i < values.Length; i++)
        {
            _csv.WriteField(values[i]);
        }
        _csv.NextRecord();
        _csv.Flush();
    }

    public void Dispose()
    {
        _csv.Dispose();
        _stream.Dispose();
        _fileStream.Close();
        _fileStream.Dispose();
    }
}