using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace InABox.Core
{
    public interface IFixedWidthImporter
    {
        int[] ColumnWidths { get; set; }
    }

    public class FixedWidthImporter<T> : BaseImporter<T>, IFixedWidthImporter where T : Entity, IRemotable, IPersistent, new()
    {
        private StreamReader _reader;

        public FixedWidthImporter()
        {
            ColumnWidths = new[] { 1024 };
        }

        public int[] ColumnWidths { get; set; }

        public override bool Open(Stream stream)
        {
            _reader = new StreamReader(stream);
            return true;
        }

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


        public override bool ReadHeader()
        {
            var result = true;
            var fields = new List<string>();
            if (HasHeader)
            {
                for (var i = 1; i < HeaderRow; i++)
                {
                    if (_reader.EndOfStream)
                        return false;
                    _reader.ReadLine();
                }

                if (_reader.EndOfStream)
                    return false;
                var buffer = _reader.ReadLine();
                var iOffset = 0;
                foreach (var columnwidth in ColumnWidths)
                {
                    var colname = string.Concat(buffer.Skip(iOffset).Take(columnwidth)).Trim();
                    fields.Add(colname);
                    iOffset += columnwidth;
                }
            }
            else
            {
                for (var i = 0; i < ColumnWidths.Length; i++)
                    fields.Add(string.Format("Column {0}", i + 1));
            }

            Fields = fields.ToArray();
            return true;
        }

        public override bool MoveNext()
        {
            return !_reader.EndOfStream;
        }

        public override Dictionary<string, string> ReadLine()
        {
            var results = new Dictionary<string, string>();

            var fields = new List<string>();
            var buffer = _reader.ReadLine();
            var iOffset = 0;
            foreach (var columnwidth in ColumnWidths)
            {
                var data = string.Concat(buffer.Skip(iOffset).Take(columnwidth)).Trim();
                fields.Add(data);
                iOffset += columnwidth;
            }

            for(int i = 0; i < Fields.Length; ++i)
            {
                results[Fields[i]] = fields[i];
            }

            return results;
        }
    }
}