package client.renderer.texture;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import client.renderer.GlState;
import common.collect.Maps;
import common.log.Log;

public class TextureManager {
	private final Map<String, Texture> textures = Maps.<String, Texture>newHashMap();

	public void bindTexture(String res) {
		Texture tex = this.textures.get(res);
		if(tex == null) {
			tex = new SimpleTexture(res);
			this.loadTexture(res, tex);
		}
		GlState.bindTexture(tex.getGlTextureId());
	}

	public boolean loadTexture(String res, Texture tex) {
		boolean flag = true;
		try {
			tex.loadTexture();
		}
		catch(IOException e) {
			if(e instanceof FileNotFoundException)
				Log.IO.warn("Textur ist nicht vorhanden: " + res);
			else
				Log.IO.error(e, "Konnte Textur nicht laden: " + res);
			tex = TextureUtil.MISSING;
			this.textures.put(res, tex);
			flag = false;
		}
		this.textures.put(res, tex);
		return flag;
	}

	public Texture getTexture(String res) {
		return this.textures.get(res);
	}

	public void deleteTexture(String res) {
		Texture tex = this.getTexture(res);
		if(tex != null)
			GlState.deleteTexture(tex.getGlTextureId());
		this.textures.remove(res);
	}

	public void onReload() {
		for(Entry<String, Texture> entry : this.textures.entrySet()) {
			this.loadTexture(entry.getKey(), entry.getValue());
		}
	}
}
