using System.Collections.Generic;
using Dapper;

namespace DapperExtensions
{
    /// <summary>
    /// 多结果Reader接口
    /// </summary>
    public interface IMultipleResultReader
    {
        /// <summary>
        /// Read the next grid of results
        /// </summary>
        /// <typeparam name="T">泛型约束</typeparam>
        /// <returns></returns>
        IEnumerable<T> Read<T>();
    }

    /// <summary>
    /// GridReaderResultReader
    /// </summary>
    public class GridReaderResultReader : IMultipleResultReader
    {
        private readonly SqlMapper.GridReader _reader;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="reader"></param>
        public GridReaderResultReader(SqlMapper.GridReader reader)
        {
            _reader = reader;
        }

        /// <summary>
        /// Read the next grid of results
        /// </summary>
        /// <typeparam name="T">泛型约束</typeparam>
        /// <returns></returns>
        public IEnumerable<T> Read<T>()
        {
            return _reader.Read<T>();
        }
    }

    /// <summary>
    /// SequenceReaderResultReader
    /// </summary>
    public class SequenceReaderResultReader : IMultipleResultReader
    {
        private readonly Queue<SqlMapper.GridReader> _items;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="items"></param>
        public SequenceReaderResultReader(IEnumerable<SqlMapper.GridReader> items)
        {
            _items = new Queue<SqlMapper.GridReader>(items);
        }

        /// <summary>
        /// Read the next grid of results
        /// </summary>
        /// <typeparam name="T">泛型约束</typeparam>
        /// <returns></returns>
        public IEnumerable<T> Read<T>()
        {
            SqlMapper.GridReader reader = _items.Dequeue();
            return reader.Read<T>();
        }
    }
}