using System;
using System.Collections;
using System.Collections.Generic;
using SlatedGameToolkit.Tools.CommandSystem.Interaction;

namespace SlatedGameToolkit.Tools.CommandSystem
{
    public class CommandMap : ICollection<IInvocable>, IDisposable {
        Dictionary<string, IInvocable> invocations;
        HashSet<IInvocable> values;

        public int Count => invocations.Count;

        public bool IsReadOnly => false;

        public IInvocable this[string invocation] {
            get {
                IInvocable result = null;
                invocations.TryGetValue(invocation, out result);
                return result;
            }
        }
        public CommandMap(params IInvocable[] invokables) {
            invocations = new Dictionary<string, IInvocable>();
            values = new HashSet<IInvocable>();
            foreach (IInvocable item in invokables)
            {
                Add(item);
            }
        }

        public IEnumerator<IInvocable> GetEnumerator()
        {
            return values.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return values.GetEnumerator();
        }

        public void Add(IInvocable item)
        {
            values.Add(item);
            string[] invokers = item.GetInvokers();
            foreach (string invoker in invokers)
            {
                try {
                    invocations.Add(invoker, item);
                } catch (ArgumentException e) {
                    throw new ArgumentException("A duplicate invocation string was found!", e);
                }
            }
        }

        public void Clear()
        {
            invocations.Clear();
            values.Clear();
        }

        public bool Contains(IInvocable item)
        {
            return values.Contains(item);
        }

        public void CopyTo(IInvocable[] array, int arrayIndex)
        {
            values.CopyTo(array, arrayIndex);
        }

        public bool Remove(IInvocable item)
        {
            string[] invokers = item.GetInvokers();
            foreach (string invoker in invokers)
            {
                if (!invocations.Remove(invoker)) return false;
            }
            values.Remove(item);
            return true;
        }

        public void Dispose()
        {
            foreach (IInvocable invocable in this)
            {
                invocable.Dispose();
            }
        }

        ~CommandMap() {
            Dispose();
        }
    }
}