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

namespace PkmnLibSharp.Library.Moves
{
    public class MoveLibrary : PointerWrapper
    {
        private readonly Dictionary<string, MoveData> _cache = new Dictionary<string, MoveData>(StringComparer.InvariantCultureIgnoreCase);
        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 = new MoveData(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 move))
            {
                _cache.Add(key, move);
                return move;
            }
            move = new MoveData(ptr);
            _cache.Add(key, move);
            return move;
        }

        public static MoveLibrary Create(ulong defaultCapacity)
        {
            var ptr = IntPtr.Zero;
            AttackLibrary.Construct(ref ptr, defaultCapacity).Assert();
            return new MoveLibrary(ptr);
        }
        
        private MoveLibrary(IntPtr ptr) : base(ptr)
        {
        }

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