module jg {
	export class LoadingScene extends Scene {
		resource:Resource;
		shape:Shape;
		shapeP:Shape;
		requestCount:number;
		finished:Trigger;
		game:Game;

		constructor(game:Game, resource:Resource) {
			super(game);
			this.game = game;
			this.resource = resource;
			this.resource.loaded.handle(this, this.complete);
			this.resource.added.handle(this, this.added);
			this.requestCount = this.resource.requests.length;
			this.finished = new Trigger();

			this.init();
		}

		init() {
			this.shape = new Shape(this.game.width, 32);
			this.shape.moveTo(0, this.game.height / 2 - 16);

			this.shapeP = new Shape(1, 32, ShapeStyle.Fill);
			this.shapeP.moveTo(0, this.game.height / 2 - 16);

			this.append(this.shape);
			this.append(this.shapeP);
		}

		animate(per:number) {
			this.shapeP.width = this.game.width * per;
			this.shapeP.updated();
		}

		complete(cnt:number) {
			var per = (this.requestCount-cnt) / this.requestCount;
			this.animate(per);

			if (per == 1) {
				this.resource.loaded.remove(this, this.complete);
				this.resource.added.remove(this, this.added);
				this.end();
				this.finished.fire();
			}
		}

		added(e:any) {
			this.requestCount++;
		}
	}
}