package speiger.src.coreengine.assets.reloader;

import java.util.Set;

import speiger.src.collections.objects.sets.ObjectLinkedOpenHashSet;

public class ResourceReloader
{
	Set<IReloadableResource> resources = new ObjectLinkedOpenHashSet<>();
	boolean globalRemoval = false;
	boolean reloading = false;
	
	public <T extends IReloadableResource> T addReloadableResource(T resource) {
		return addReloadableResource(resource, false);
	}
	
	public <T extends IReloadableResource> T addReloadableResource(T resource, boolean init) {
		if(resources.add(resource) && init) resource.reload();
		return resource;
	}
	
	public void removeReloadableResource(IReloadableResource resource) {
		if(globalRemoval || reloading) return;
		resources.remove(resource);
	}
	
	public boolean isReloading() { return reloading; }
	
	public void reloadResources() {
		reloading = true;
		resources.forEach(IReloadableResource::reload);
		reloading = false;
	}
	
	public void deleteResources() {
		globalRemoval = true;
		resources.forEach(IReloadableResource::destroy);
		resources.clear();
		globalRemoval = false;
	}
}
