using JetBrains.Annotations;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using TextFieldParserStandard;

namespace InABox.Scripting
{
    public class DelimitedFileReader : ITabularFileReader, IDisposable
    {
        private TextFieldParser _parser;

        public bool EndOfData => _parser.EndOfData;

        public Dictionary<string, int> Columns { get; set; }

        public DelimitedFileReader(Stream stream, string delimiter)
        {
            _parser = new TextFieldParser(stream);
            _parser.TextFieldType = FieldType.Delimited;
            _parser.SetDelimiters(delimiter);

            Columns = new();
        }

        public bool ReadHeader()
        {
            if (_parser.EndOfData)
            {
                return false;
            }
            Columns = _parser.ReadFields().Select((field, i) => (field, i)).ToDictionary(x => x.field, x => x.i);
            return true;
        }

        public bool SkipLine()
        {
            if (_parser.EndOfData)
            {
                return false;
            }
            _parser.ReadLine();
            return true;
        }

        public Dictionary<string, object?> ReadLine()
        {
            var values = _parser.ReadFields();
            return Columns.ToDictionary<KeyValuePair<string, int>, string, object?>(
                x => x.Key,
                x =>
                {
                    object? result = x.Value < values.Length ? values[x.Value] : null;
                    return result;
                });
        }

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

        public IList<string> ReadLineValues() => _parser.ReadFields();
    }
}
