using InABox.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Syncfusion.Windows.Tools.Controls;
using System.Threading;
using System.Windows;

namespace InABox.DynamicGrid;


public interface IDynamicItemsListGrid : IDynamicGrid
{
    /// <summary>
    /// The items list that forms the source for the rows of this grid
    /// </summary>
    /// <remarks>
    /// <b>Note:</b> This must be a list of type <see cref="List{T}"/>, otherwise the assignment to this property <u>will not</u> work.
    /// </remarks>
    IList Items { get; set; }
    
}

public class DynamicItemsListGrid<T> : DynamicGrid<T>, IDynamicItemsListGrid
    where T : BaseObject, new()
{
    
    private List<T> _items = [];

    public List<T> Items
    { 
        get => _items; 
        set => _items = value; 
    }

    IList IDynamicItemsListGrid.Items
    {
        get => _items; 
        set => _items = value as List<T> ?? new List<T>();
    }
    
    public override void OnItemSourceChanged(object value)
    {
        if (value is List<T> list)
        {
            Items = list;
            Refresh(true,true);
        }
    }

    protected override void Init()
    {
    }

    protected override void DoReconfigure(DynamicGridOptions options)
    {
        
    }


    public override void DeleteItems(params CoreRow[] rows)
    {
        foreach (var row in rows.OrderByDescending(x => x.Index))
        {
            Items.RemoveAt(_recordmap[row].Index);
        }
    }

    public override T LoadItem(CoreRow row)
    {
        return Items[_recordmap[row].Index];
    }

    protected override void Reload(
        Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort, 
        CancellationToken token, Action<CoreTable?, Exception?> action)
    {
        var result = new CoreTable();
        result.LoadColumns(columns);
        result.LoadRows(Items);
        action.Invoke(result, null);
    }

    public override void SaveItem(T item)
    {
        if (!Items.Contains(item))
        {
            Items.Add(item);
        }
        if (item is ISequenceable)
        {
            Items.Sort((a, b) => (a as ISequenceable)!.Sequence.CompareTo((b as ISequenceable)!.Sequence));
        }
    }

    protected override bool BeforeCopy(IList<T> items)
    {
        if (!base.BeforeCopy(items)) return false;

        for(int i = 0; i < items.Count; ++i)
        {
            items[i] = items[i].Clone();
        }
        return true;
    }
}
