
Engine.GraphicFactory = class {

	constructor()
	{
		this.graphicDataByName = {};
		this.graphicNameById = {};

		this.loadingGraphicsCallbacks = {};
	}

	getGraphicDefByID(graphic_id)
	{
		return this.getGraphicById(graphic_id);
	}

	getGraphicById(graphic_id)
	{
		return this.getGraphicDataByName(this.getGraphicNameById(graphic_id));
	}

	getGraphicNameById(graphic_id)
	{
		if (this.graphicNameById[graphic_id])
		{
			return this.graphicNameById[graphic_id];
		}
	}

	getGraphicDefByName(name, width, height)
	{
		return this.getGraphicDataByName(name, width, height);
	}

	getGraphicDataByName(name, width, height)
	{
		if (this.graphicDataByName[name])
		{
			var graphicData = this.graphicDataByName[name];
			if(width !== undefined && height !== undefined)
			{
				graphicData = graphicData.getAlternateDefBySize(width, height);
			}
			return graphicData;
		}
	}

	addGraphicData(graphicData)
	{
		//This is checking to see if the graphic listed here was already added. This is likely from a preloaded pack...
		if (this.graphicDataByName[graphicData.name] !== undefined)
		{
			if (this.graphicDataByName[graphicData.name].id == -1 && graphicData.id != -1)
			{
				this.graphicDataByName[graphicData.name].id = graphicData.id;
			}
		} 
		else 
		{
			this.graphicDataByName[graphicData.name] = graphicData;
		}

		this.graphicNameById[graphicData.id] = graphicData.name;
	}

	loadGraphicData(graphicData, callback)
	{
		// this gets hit by parallaxBackground
		if (callback === undefined) 
		{
			callback = () => 
			{ 
				Debug.Log("Load Graphic Data noop callback...")
			}
		}

		if (this.loadingGraphicsCallbacks[graphicData.url])
		{
			this.loadingGraphicsCallbacks[graphicData.url].push(callback);
		} 
		else 
		{
			this.loadGraphicDataFromURL(graphicData.url, callback, () => graphicData.loadFailed());
			this.loadingGraphicsCallbacks[graphicData.url] = [];
		}	
	}

	loadGraphicDataFromURL(url, callback, errorCallback)
	{
		var t = this;
		var graphicLoader = new Engine.GraphicLoader();
		graphicLoader.load(url, function(graphicData) { t.graphicsLoaded(url, graphicData, callback);}, errorCallback);
	}

	graphicsLoaded(url, graphicData, callback)
	{
		for (var g in graphicData)
		{
			this.graphicDataByName[g] = graphicData[g];
			this.graphicNameById[graphicData[g].id] = graphicData[g].name;

			//console.log(graphicData[g].name);
		}

		//console.log(url+ "******************************************************");

		callback();

		if (this.loadingGraphicsCallbacks[url])
		{
			for (var i = 0; i < this.loadingGraphicsCallbacks[url].length; i++)
			{
				try{
					this.loadingGraphicsCallbacks[url][i]();
				} 
				catch(e)
				{
					Debug.Log(url + " : " + i+ " No callback?");
				}
			}
			delete this.loadingGraphicsCallbacks[url];
		}
	}

	unloadGraphicDef(def)
	{
		Debug.Log("TODO: Unload graphic " + (def ? def.name : "UNKNOWN") +" Implement UNLOAD!...");
	}
}