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

namespace InABox.DynamicGrid;

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

    protected override void DoReconfigure(DynamicGridOptions options)
    {
        base.DoReconfigure(options);
        options.Clear();
        options.SelectColumns = true;
    }

    public override DynamicGridColumns GenerateColumns()
    {
        var columns = base.GenerateColumns();
        var prefix = $"{typeof(TLeft).Name}.";
        columns.RemoveAll(x => x.ColumnName.StartsWith(prefix));
        return columns;
    }

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