namespace Nerfed.Runtime;

public static class ResourceManager
{
    private const string rootName = "Resources";
    private static readonly Dictionary<string, Resource> loadedResources = new Dictionary<string, Resource>();

    public static T Load<T>(string resourcePath) where T : Resource
    {
        if (loadedResources.TryGetValue(resourcePath, out Resource resource))
        {
            return (T)resource;
        }

        if (typeof(T) == typeof(Shader))
        {
            resource = new Shader();
        }
        else
        {
            throw new Exception("Failed to create resource");
        }

        Assert.Always(resource != null);
        resource.Path = resourcePath;
        resource.Load(StorageContainer.OpenStream(Path.Combine(AppContext.BaseDirectory, rootName, resourcePath) + ".bin"));

        loadedResources.Add(resourcePath, resource);
        return (T)resource;
    }

    public static void Unload(Resource resource)
    {
        if (!loadedResources.ContainsKey(resource.Path))
        {
            return;
        }

        resource.Unload();
        resource.Path = string.Empty;
        loadedResources.Remove(resource.Path);
    }
}
