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

namespace PkmnLibSharp.Library
{
    public class SpeciesLibrary : PointerWrapper
    {
        private readonly Dictionary<string, Species> _cache = new Dictionary<string, Species>(StringComparer.InvariantCultureIgnoreCase);
        public ulong Count => Creatureliblibrary.Generated.SpeciesLibrary.GetCount(Ptr);

        public void Insert(string key, Species species)
        {
            Creatureliblibrary.Generated.SpeciesLibrary.Insert(Ptr, key.ToPtr(), species.Ptr).Assert();
            _cache.Add(key, species);
        }

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

        public bool TryGet(string key, out Species species)
        {
            if (_cache.TryGetValue(key, out species))
                return true;
            var ptr = IntPtr.Zero;
            if (Creatureliblibrary.Generated.SpeciesLibrary.TryGet(Ptr, key.ToPtr(), ref ptr) != MarshalHelper.True) 
                return false;
            if (TryResolvePointer(ptr, out species))
            {
                _cache.Add(key, species);
                return true;
            }
            species = new Species(ptr);
            _cache.Add(key, species);
            return true;
        }

        public Species Get(string key)
        {
            if (_cache.TryGetValue(key, out var species))
                return species;
            var ptr = IntPtr.Zero;
            Creatureliblibrary.Generated.SpeciesLibrary.Get(Ptr, key.ToPtr(), ref ptr).Assert();
            if (TryResolvePointer(ptr, out species))
            {
                _cache.Add(key, species);
                return species;
            }
            species = new Species(ptr);
            _cache.Add(key, species);
            return species;
        }

        public SpeciesLibrary(ulong initialCapacity) : base(
            Creatureliblibrary.Generated.SpeciesLibrary.Construct(initialCapacity))
        {
        }

        protected override void DeletePtr()
        {
            Creatureliblibrary.Generated.SpeciesLibrary.Destruct(Ptr);
        }
    }
}