using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InABox.Avalonia.Components;

public class AvaloniaDataGridColumns : IList<IAvaloniaDataGridColumn>
{
    private readonly List<IAvaloniaDataGridColumn> _columns = new();

    public IAvaloniaDataGridColumn this[int index]
    {
        get => _columns[index];
        set
        {
            _columns[index] = value;
            DoChanged();
        }
    }

    public int Count => _columns.Count;

    public bool IsReadOnly => false;

    private bool _observing = true;
    private bool _changed = false;

    public delegate void ChangedEventHandler(AvaloniaDataGridColumns columns);

    public event ChangedEventHandler? Changed;

    public AvaloniaDataGridColumns BeginUpdate()
    {
        _observing = false;
        return this;
    }
    public AvaloniaDataGridColumns EndUpdate()
    {
        _observing = true;
        if (_changed)
        {
            DoChanged();
        }
        return this;
    }

    private void DoChanged()
    {
        if (!_observing)
        {
            _changed = true;
            return;
        }
        Changed?.Invoke(this);
        _changed = false;
    }

    public AvaloniaDataGridColumns Add(IAvaloniaDataGridColumn item)
    {
        _columns.Add(item);
        DoChanged();
        return this;
    }
    void ICollection<IAvaloniaDataGridColumn>.Add(IAvaloniaDataGridColumn item)
    {
        Add(item);
    }

    public AvaloniaDataGridColumns Clear()
    {
        _columns.Clear();
        DoChanged();
        return this;
    }
    void ICollection<IAvaloniaDataGridColumn>.Clear()
    {
        Clear();
    }

    public AvaloniaDataGridColumns AddRange(IEnumerable<IAvaloniaDataGridColumn> items)
    {
        _columns.AddRange(items);
        DoChanged();
        return this;
    }

    public bool Contains(IAvaloniaDataGridColumn item) => _columns.Contains(item);

    public void CopyTo(IAvaloniaDataGridColumn[] array, int arrayIndex)
    {
        _columns.CopyTo(array, arrayIndex);
    }

    public IEnumerator<IAvaloniaDataGridColumn> GetEnumerator()
    {
        return _columns.GetEnumerator();
    }

    public int IndexOf(IAvaloniaDataGridColumn item) => _columns.IndexOf(item);

    public void Insert(int index, IAvaloniaDataGridColumn item)
    {
        _columns.Insert(index, item);
        DoChanged();
    }

    public bool Remove(IAvaloniaDataGridColumn item)
    {
        if (_columns.Remove(item))
        {
            DoChanged();
            return true;
        }
        else
        {
            return false;
        }
    }

    public void RemoveAt(int index)
    {
        _columns.RemoveAt(index);
        DoChanged();
    }

    IEnumerator IEnumerable.GetEnumerator() => _columns.GetEnumerator();
}
