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

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

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

        public ulong Count => AttackLibrary.GetCount(Ptr);

        public void Insert(string key, MoveData move)
        {
            AttackLibrary.Insert(Ptr, key.ToPtr(), move.Ptr).Assert();
            _cache.Add(key, move);
        }

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

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

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

        public MoveData Get(string key)
        {
            if (_cache.TryGetValue(key, out var move))
                return move;
            var ptr = IntPtr.Zero;
            AttackLibrary.Get(Ptr, key.ToPtr(), ref ptr).Assert();
            if (TryResolvePointer(ptr, out MoveData? m))
            {
                _cache.Add(key, m!);
                return m!;
            }

            move = Constructor.Active.ConstructMove(ptr)!;
            _cache.Add(key, move);
            return move;
        }

        public MoveLibrary(ulong defaultCapacity)
        {
            var ptr = IntPtr.Zero;
            AttackLibrary.Construct(ref ptr, defaultCapacity).Assert();
            Initialize(ptr);
        }
        
        public IEnumerable<MoveData> GetEnumerator()
        {
            var count = AttackLibrary.GetCount(Ptr);
            var ptr = IntPtr.Zero;
            for (ulong i = 0; i < count; i++)
            {
                AttackLibrary.GetAtIndex(Ptr, i, ref ptr).Assert();
                if (TryResolvePointer(ptr, out MoveData? move))
                    yield return move!;
                else
                    yield return Constructor.Active.ConstructMove(ptr)!;
            }
        }

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

        protected override void DeletePtr()
        {
            AttackLibrary.Destruct(Ptr);
        }
    }
}