﻿using System;
using System.Collections.Generic;
using System.Data;

namespace Nickymaco.SQL.Iterator
{
    public class DynamicObjectRecordsReaderIterator : IEnumerator<DynamicExtentObject>
    {
        private bool _disposed = false;
        private bool _moveNext = true;
        private IRecordsReader _reader;
        private readonly DataTable _schemaTable;
        private readonly DynamicExtentObject _current;

        public DynamicObjectRecordsReaderIterator(IRecordsReader read)
        {
            _reader = read;
            _schemaTable = read.GetSchemaTable();
            _current = new DynamicExtentObject();
        }

        ~DynamicObjectRecordsReaderIterator()
        {
            Dispose();
        }

        public bool HasRecords
        {
            get
            {
                return _reader.HasRecords;
            }
        }

        public DynamicExtentObject Current
        {
            get
            {
                if (!_moveNext)
                {
                    return null;
                }
                else
                {
                    _current.Clear();

                    for (var i = 0; i < _schemaTable.Rows.Count; i++)
                    {
                        string fieldName = _schemaTable.Rows[i]["ColumnName"].ToString();

                        _current.Add(fieldName, _reader[fieldName]);
                    }

                    return _current;
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposed)
        {
            if (!_disposed)
            {
                if (disposed)
                {
                    if (_reader != null && !_reader.IsClosed)
                    {
                        _reader.Close();
                        _reader.Dispose();
                        _reader = null;
                    }
                }
                _disposed = true;
            }
        }

        object System.Collections.IEnumerator.Current
        {
            get { return this.Current; }
        }

        public bool MoveNext()
        {
            return _moveNext = _reader.Read();
        }

        public void Reset()
        {
            throw new Exception("The data reader pointer can not go back.");
        }
    }
}
