using System;
using System.Collections.Generic;
using PkmnLibSharp.Utilities;

namespace PkmnLibSharp.Library.Items
{
    public class ItemLibrary : PointerWrapper
    {
        private readonly Dictionary<string, Item> _cache =
            new Dictionary<string, Item>(StringComparer.InvariantCultureIgnoreCase);

        internal ItemLibrary(IntPtr ptr) : base(ptr)
        {
        }

        public ItemLibrary(ulong initialCapacity) : base(
            Creaturelib.Generated.ItemLibrary.Construct(initialCapacity))
        {
        }

        public ulong Count => Creaturelib.Generated.ItemLibrary.GetCount(Ptr);

        public void Insert(string key, Item item)
        {
            Creaturelib.Generated.ItemLibrary.Insert(Ptr, key.ToPtr(), item.Ptr).Assert();
            _cache.Add(key, item);
        }

        public void Delete(string key)
        {
            Creaturelib.Generated.ItemLibrary.Delete(Ptr, key.ToPtr()).Assert();
            _cache.Remove(key);
        }

        public bool TryGet(string key, out Item? item)
        {
            if (_cache.TryGetValue(key, out item))
                return true;
            var ptr = IntPtr.Zero;
            if (Creaturelib.Generated.ItemLibrary.TryGet(Ptr, key.ToPtr(), ref ptr) != MarshalHelper.True)
                return false;
            if (TryResolvePointer(ptr, out item))
            {
                _cache.Add(key, item!);
                return true;
            }

            item = Constructor.Active.ConstructItem(ptr)!;
            _cache.Add(key, item);
            return true;
        }

        public Item Get(string key)
        {
            if (_cache.TryGetValue(key, out var item))
                return item;
            var ptr = IntPtr.Zero;
            Creaturelib.Generated.ItemLibrary.Get(Ptr, key.ToPtr(), ref ptr).Assert();
            if (TryResolvePointer(ptr, out Item? i))
            {
                _cache.Add(key, i!);
                return i!;
            }

            item = Constructor.Active.ConstructItem(ptr)!;
            _cache.Add(key, item);
            return item;
        }
        
        public IEnumerable<Item> GetEnumerator()
        {
            var count = Creaturelib.Generated.ItemLibrary.GetCount(Ptr);
            var ptr = IntPtr.Zero;
            for (ulong i = 0; i < count; i++)
            {
                Creaturelib.Generated.ItemLibrary.GetAtIndex(Ptr, i, ref ptr).Assert();
                if (TryResolvePointer(ptr, out Item? item))
                    yield return item!;
                else
                    yield return Constructor.Active.ConstructItem(ptr)!;
            }
        }

        protected internal override void MarkAsDeleted()
        {
            base.MarkAsDeleted();
            foreach (var item in _cache) item.Value.MarkAsDeleted();
        }

        protected override void DeletePtr()
        {
            Creaturelib.Generated.ItemLibrary.Destruct(Ptr);
        }
    }
}