using InABox.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace InABox.DynamicGrid
{
    public class DynamicCrossJoinGrid<TEntity, TLeft> : DynamicDataGrid<TEntity>
        where TEntity : Entity, IRemotable, IPersistent, new()
        where TLeft : Entity
    {
        public TLeft Left { get; set; }
        public Expression<Func<TEntity, Guid>> LeftMapping { get; set; }
        public Expression<Func<TLeft, Guid>> LeftProperty { get; set; }

        public DynamicCrossJoinGrid(TLeft left, Expression<Func<TEntity, Guid>> leftMapping, Expression<Func<TLeft, Guid>> leftProperty)
        {
            Left = left;
            LeftMapping = leftMapping;
            LeftProperty = leftProperty;

            Options.BeginUpdate().Clear().Add(DynamicGridOption.FilterRows).Add(DynamicGridOption.SelectColumns).EndUpdate();
        }
        protected override void GenerateColumns(DynamicGridColumns columns)
        {
            base.GenerateColumns(columns);
            var prefix = $"{typeof(TLeft).Name}.";
            columns.RemoveAll(x => x.ColumnName.StartsWith(prefix));
        }

        protected override void Reload(Filters<TEntity> criteria, Columns<TEntity> columns, ref SortOrder<TEntity>? sort, Action<CoreTable?, Exception?> action)
        {
            var filter = new Filter<TEntity>();
            filter.Expression = CoreUtils.ExtractMemberExpression<TEntity, Guid>(LeftMapping);
            filter.Operator = Operator.IsEqualTo;
            filter.Value = CoreUtils.GetPropertyValue(Left, CoreUtils.GetFullPropertyName(LeftProperty, "."));
            criteria.Add(filter);
            base.Reload(criteria, columns, ref sort, action);
        }
    }
}
