using System.Collections.Generic;
using System.Linq;
using Sirenix.OdinInspector;

namespace Intrepid.Utilities.Updatable
{
    public class UpdatableCollection : SingletonMonoBehaviour<UpdatableCollection>
    {
        private Dictionary<string, IUpdatable> UpdatableMap { get; } = new();
        public List<IUpdatable> OrderedUpdatableList { get; } = new();
        private List<string> AddedIds { get; } = new();
        private List<string> RemovedIds { get; } = new();
        [GroupDebug, ShowInInspector, ReadOnly] private IReadOnlyList<string> UpdatableIds => UpdatableMap.Keys.ToList();

        private void Awake()
        {
            SingletonInstantiation();
        }

        public T Get<T>(string id) where T : IUpdatable
        {
            if (!UpdatableMap.TryGetValue(id, out var t)) return default;
            return (T) t;
        }

        public void Add(IUpdatable updatable)
        {
            UpdatableMap.TryAdd(updatable.Id, updatable);
            AddedIds.Add(updatable.Id);
        }

        public void Remove(string id)
        {
            UpdatableMap.Remove(id);
            RemovedIds.Add(id);
        }
        
        public void ListOrderManagement()
        {
            var hasAddedIds = AddedIds.Count > 0;
            if (hasAddedIds)
            {
                foreach (var id in AddedIds)
                {
                    OrderedUpdatableList.Add(UpdatableMap[id]);
                }
            }
            
            var hasRemovedIds = RemovedIds.Count > 0;
            if (hasRemovedIds)
            {
                foreach (var id in RemovedIds)
                {
                    OrderedUpdatableList.RemoveAll(u => u.Id.Equals(id));
                }
            }

            if (!hasAddedIds && !hasRemovedIds) return;
            OrderedUpdatableList.Sort((u1, u2) => u1.Order.CompareTo(u2.Order));
            AddedIds.Clear();
            RemovedIds.Clear();
        }
    }
}