using System.Collections;
using System.Linq;
using System.Linq.Expressions;

namespace ZB.MOM.WW.CBDD.Core.Query;

internal class BTreeQueryable<T> : IOrderedQueryable<T>
{
    /// <summary>
    /// Initializes a new queryable wrapper for the specified provider and expression.
    /// </summary>
    /// <param name="provider">The query provider.</param>
    /// <param name="expression">The expression tree.</param>
    public BTreeQueryable(IQueryProvider provider, Expression expression)
    {
        Provider = provider;
        Expression = expression;
    }

    /// <summary>
    /// Initializes a new queryable wrapper for the specified provider.
    /// </summary>
    /// <param name="provider">The query provider.</param>
    public BTreeQueryable(IQueryProvider provider)
    {
        Provider = provider;
        Expression = Expression.Constant(this);
    }

    /// <summary>
    /// Gets the element type returned by this query.
    /// </summary>
    public Type ElementType => typeof(T);

    /// <summary>
    /// Gets the expression tree associated with this query.
    /// </summary>
    public Expression Expression { get; }

    /// <summary>
    /// Gets the query provider for this query.
    /// </summary>
    public IQueryProvider Provider { get; }

    /// <inheritdoc />
    public IEnumerator<T> GetEnumerator()
    {
        return Provider.Execute<IEnumerable<T>>(Expression).GetEnumerator();
    }

    /// <inheritdoc />
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
