package speiger.src.coreengine.rendering.textures.base;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.lists.ObjectList;
import speiger.src.collections.objects.sets.ObjectLinkedOpenHashSet;
import speiger.src.collections.objects.sets.ObjectSet;
import speiger.src.coreengine.assets.base.IAssetProvider;
import speiger.src.coreengine.assets.base.IManagedAsset;
import speiger.src.coreengine.assets.base.IReloadableAsset.ISimpleRealodableAsset;

public class TextureTracker implements ISimpleRealodableAsset, IManagedAsset {
	IAssetProvider provider;
	ObjectList<ITexture> textures = new ObjectArrayList<>();
	ObjectSet<ITexture> reloadable = new ObjectLinkedOpenHashSet<>();
	
	public void registerTexture(ITexture texture) {
		register(texture, false);
	}
	
	public void registerReloadable(ITexture texture) {
		register(texture, true);
	}
	
	public void register(ITexture texture, boolean reloadable) {
		textures.add(texture);
		if(reloadable) this.reloadable.add(texture);
		texture.load(provider);
	}
	
	public void deleteTexture(ITexture texture) {
		textures.remove(texture);
		reloadable.remove(texture);
	}
	
	@Override
	public void onAssetsReloaded(IAssetProvider provider) {
		textures.forEach(ITexture::reset);
		textures.clear();
		reloadable.peek(this::load).forEach(textures::add);
	}
	
	@Override
	public void destroy() {
		textures.forEach(ITexture::reset);
		textures.clear();
		reloadable.clear();
	}
	
	private void load(ITexture texture) {
		texture.load(provider);
	}
	
	@Override
	public String getName() { return "Texture Tracker"; }
	
	@Override
	public void setProvider(IAssetProvider provider) { this.provider = provider; }
}
