using Pilz.GeneralEventArgs;
using System.Collections;
using System.Collections.Generic;

namespace Pilz.Configuration;

public class ConfigurationManagerList : IList<ConfigurationManager>
{
    public event GettingParentManagerEventHandler GettingParentManager;

    public delegate void GettingParentManagerEventHandler(object sender, GetValueEventArgs<SimpleConfiguration> e);

    private readonly List<ConfigurationManager> myList = new List<ConfigurationManager>();

    private object GetParentManager()
    {
        var args = new GetValueEventArgs<SimpleConfiguration>();
        GettingParentManager?.Invoke(this, args);
        return args.Value;
    }

    public ConfigurationManager this[int index]
    {
        get => myList[index];
        set => myList[index] = value;
    }

    public int Count => myList.Count;

    public bool IsReadOnly => false;

    public void Insert(int index, ConfigurationManager item)
    {
        myList.Insert(index, item);
        item.SetConfiguration((SimpleConfiguration)GetParentManager());
    }

    public void RemoveAt(int index)
    {

    }

    public void Add(ConfigurationManager item)
    {
        item.SetConfiguration((SimpleConfiguration)GetParentManager());
    }

    public void Clear()
    {
        foreach (ConfigurationManager item in myList)
            item.SetConfiguration(null);
        myList.Clear();
    }

    public void CopyTo(ConfigurationManager[] array, int arrayIndex)
    {
        myList.CopyTo(array, arrayIndex);
    }

    public int IndexOf(ConfigurationManager item)
    {
        return myList.IndexOf(item);
    }

    public bool Contains(ConfigurationManager item)
    {
        return myList.Contains(item);
    }

    public bool Remove(ConfigurationManager item)
    {
        item.SetConfiguration(null);
        return myList.Remove(item);
    }

    public IEnumerator<ConfigurationManager> GetEnumerator()
    {
        return (IEnumerator<ConfigurationManager>)IEnumerable_GetEnumerator();
    }

    private IEnumerator IEnumerable_GetEnumerator()
    {
        return myList.GetEnumerator();
    }

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