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

namespace PkmnLibSharp.Library
{
    public class NatureLibrary : PointerWrapper
    {
        private readonly Dictionary<string, Nature> _cache =
            new Dictionary<string, Nature>(StringComparer.InvariantCultureIgnoreCase);
        private readonly Dictionary<IntPtr, string> _natureNames = new Dictionary<IntPtr, string>();

        public NatureLibrary(ulong initialCapacity) : base(Pkmnlib.Generated.NatureLibrary.Construct(initialCapacity))
        {
        }

        public void LoadNature(string name, Nature nature)
        {
            Pkmnlib.Generated.NatureLibrary.LoadNature(Ptr, name.ToPtr(), nature.Ptr).Assert();
            _cache.Add(name, nature);
            _natureNames.Add(nature.Ptr, name);
        }

        public Nature GetNature(string name)
        {
            if (_cache.TryGetValue(name, out var nature))
                return nature;
            var ptr = IntPtr.Zero;
            Pkmnlib.Generated.NatureLibrary.GetNatureByName(Ptr, name.ToPtr(), ref ptr).Assert();
            if (TryResolvePointer(ptr, out nature))
            {
                _cache.Add(name, nature);
                _natureNames.Add(ptr, name);
                return nature;
            }
            nature = new Nature(ptr);
            _cache.Add(name, nature);
            _natureNames.Add(ptr, name);
            return nature;
        }

        public string GetNatureName(Nature nature)
        {
            if (_natureNames.TryGetValue(nature.Ptr, out var s))
                return s;
            var ptr = IntPtr.Zero;
            Pkmnlib.Generated.NatureLibrary.GetNatureName(Ptr, nature.Ptr, ref ptr).Assert();
            return ptr.PtrString();
        }

        protected override void DeletePtr()
        {
            Pkmnlib.Generated.NatureLibrary.Destruct(Ptr);
        }
    }
}