using Nerfed.Runtime.Graphics;

namespace Nerfed.Runtime.Gui;

public class GuiTextureStorage
{
    private readonly Dictionary<IntPtr, WeakReference<Texture>> pointerToTexture = new Dictionary<IntPtr, WeakReference<Texture>>();

    public IntPtr Add(Texture texture)
    {
        if (!pointerToTexture.ContainsKey(texture.Handle))
        {
            pointerToTexture.Add(texture.Handle, new WeakReference<Texture>(texture));
        }
        return texture.Handle;
    }

    public Texture GetTexture(IntPtr pointer)
    {
        if (!pointerToTexture.TryGetValue(pointer, out WeakReference<Texture> value))
        {
            return null;
        }

        WeakReference<Texture> result = value;

        if (!result.TryGetTarget(out Texture texture))
        {
            pointerToTexture.Remove(pointer);
            return null;
        }

        return texture;
    }
}