/**
* WebGL Model Viewer - TextureLibrary.js
* Copyright © Cyril Diagne 2010.
*
* @author kikko.fr
*/

var TextureLibrary = TextureLibrary || {
	
	currLoad : 0,
	imagesToLoad : [],
	events : new EventDispatcher(),
	path : "",
	textures : {},
	
	getTexture : function(url) {
	
		if(!this.textures[url]) {
			this.textures[url] = { url:url, glTexture:gl.createTexture(), image:null };
			this.imagesToLoad.push(url);
		}
		
		return this.textures[url].glTexture;
	},
	
	load : function(texturesURL) {
		
		this.path = texturesURL || this.path;
		
		if(this.imagesToLoad.length == 0) {
			log("TextureLibrary - No files to load.");
			this.events.dispatchEvent("texturesLoaded", this);
			return;
		}
	
		log("TextureLibrary - Loading:", this.imagesToLoad.length, "files...");
		this.currLoad = 0;
		this.loadNext();
	},
	
	loadNext : function() {
		
		var url = this.imagesToLoad[this.currLoad];
		
		var textureInfo = this.textures[url];
		if (textureInfo.image) {
			log("TextureLibrary - skip loading for", url);
			this.handleLoadedTexture();
			return;
		}
		
		textureInfo.image = new Image();
		textureInfo.image.addEventListener("load", delegate(this, this.handleLoadedTexture), false);
		textureInfo.image.addEventListener("error", delegate(this, this.loadError), false);
		textureInfo.image.src = this.path + url;
		
		log("TextureLibrary - Loading:", url, "...");
	},
	
	loadError : function(event) {
		log("TextureLibrary - Load Error. Aborting.", this.imagesToLoad[this.currLoad]);
	},
	
	handleLoadedTexture : function(event) {
		
		if(event) {
			var url = this.imagesToLoad[this.currLoad];
			this.initTexture(this.textures[url], event.target, gl.LINEAR, gl.LINEAR);
			log("TextureLibrary - Loaded.");
		}
		
		if(this.currLoad++ >= this.imagesToLoad.length-1) {
			log("TextureLibrary - Done.");
			this.imagesToLoad = [];
			this.events.dispatchEvent("texturesLoaded", this);
			
		}
		else this.loadNext();
	},
	
	initTexture : function(textureInfos, image, magFilter, minFilter) {
		
		gl.bindTexture(gl.TEXTURE_2D, textureInfos.glTexture);
		gl.texImage2D(gl.TEXTURE_2D, 0, textureInfos.image, true);
		//gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureInfos.image);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
		
		if(minFilter == gl.LINEAR_MIPMAP_NEAREST) gl.generateMipmap(gl.TEXTURE_2D);
		
		gl.bindTexture(gl.TEXTURE_2D, null);		
	}
}
