using System;
using System.Collections.Generic;
using System.IO;
using TextFieldParserStandard;

namespace InABox.Core
{
    public abstract class DelimitedImporter<T> : BaseImporter<T> where T : Entity, IRemotable, IPersistent, new()
    {
        private TextFieldParser _parser;

        protected abstract string Delimiter { get; }

        public override bool Open(Stream stream)
        {
            _parser = new TextFieldParser(stream);
            _parser.TextFieldType = FieldType.Delimited;
            _parser.SetDelimiters(Delimiter);

            return true;
        }

        public override void Close()
        {
            _parser?.Dispose();
            _parser = null;
        }

        public override bool ReadHeader()
        {
            for (var i = 1; i < HeaderRow; i++)
            {
                if (_parser.EndOfData)
                    return false;
                _parser.ReadLine();
            }

            if (_parser.EndOfData)
                return false;
            Fields = _parser.ReadLine().Split(','); //.Select(x=>x.Replace(" ","_")).ToArray();
            return true;
        }

        public override bool MoveNext()
        {
            return !_parser.EndOfData;
        }

        public override Dictionary<string, string> ReadLine()
        {
            var results = new Dictionary<string, string>();
            var fields = _parser.ReadFields();
            for(int i = 0; i < Fields.Length; ++i)
            {
                results[Fields[i]] = fields[i];
            }

            return results;
        }
    }
}