class Resource {
	images: {[key:string]: HTMLImageElement; };
	requests: any[];
	loaded: Trigger;

	static instance:Resource;

	static getInstance():Resource {
		return () => {
			if (! Resource.instance)
				Resource.instance = new Resource();
			return Resource.instance;
		}();
	}

	constructor() {
		this.requests = [];
		this.loaded = new Trigger();
		this.images = {};
	}

	get(name:string) {
		return this.images[name];
	}

	loadImage(url:string, identifier:string, caller:any, callback?:(string,HTMLImageElement, bool) => void) {
		var image = new Image();
		image.src = "img/"+url;
		image.onerror = function() {
			callback.call(caller, identifier, image, false);
		};
		image.onload = function() {
			callback.call(caller, identifier, image, true);
		};
	}

	loadImageComplete(name:string, image:HTMLImageElement, is_success:bool) {
		if (! is_success) {
			console.log("error: "+name);
		} else {
			this.images[name] = image;
		}
		for (var i=0; i<this.requests.length; i++) {
			if (this.requests[i] == name) {
				this.requests.splice(i, 1);
				break;
			}
		}
		this.loaded.fire(this.requests.length);
	}

	load(name:string, url?:string) {
		if (! url)
			url = name;

		this.requests.push(name);
		this.loadImage(url, name, this, this.loadImageComplete);
	}
}