module GBJam5 {
	export class Unit {
		walkSpeed: number = 2;

		game: Phaser.Game = null;

		sprite: Phaser.Sprite = null;

		aStar: Phaser.Plugin.AStar = null;
		path: Phaser.Plugin.AStar.AStarPath = null;
		currentNodeId: number = null;
		goalTileIndex: Phaser.Point = null;
		isWalking: boolean = false;
		walkTimer: number = 1000 / this.walkSpeed;

		tileIndex: Phaser.Point = null;

		constructor(game: Phaser.Game, aStar: Phaser.Plugin.AStar) {
			this.game = game;
			this.aStar = aStar;
		}

		spawn(tileIndex: Phaser.Point) {
			this.tileIndex = tileIndex;
			this.sprite.x = this.tileIndex.x * tileSize;
			this.sprite.y = this.tileIndex.y * tileSize;
		}

		goTo(goalTileIndex: Phaser.Point) {
			this.goalTileIndex = goalTileIndex;
		}

		update() {
			if (this.isWalking) {
				this.walkTimer -= this.game.time.elapsedMS;

				var spritePos = this.sprite.position;

				if (this.walkTimer <= 0) {
					// determine next node
					var currentNode = this.path.nodes[--this.currentNodeId];
					this.tileIndex = new Phaser.Point(currentNode.x, currentNode.y);
					spritePos.x = this.tileIndex.x * tileSize;
					spritePos.y = this.tileIndex.y * tileSize;

					// at goal or new goal
					if ((this.currentNodeId <= 0) || (this.goalTileIndex != null)) {
						this.path = null;
						this.currentNodeId = null;
						this.isWalking = false;
						this.sprite.animations.play('idle');
					}

					this.walkTimer = 1000 / this.walkSpeed;
				} else {
					// intermediate walking anim
					var currentNode = (this.currentNodeId == this.path.nodes.length) ? this.path.start : this.path.nodes[this.currentNodeId];
					var nextNode = this.path.nodes[this.currentNodeId - 1];

					var lerpDelta = ((1000 / this.walkSpeed) - this.walkTimer) / (1000 / this.walkSpeed);
					spritePos.x = (currentNode.x * tileSize) + (((nextNode.x - currentNode.x) * tileSize) * lerpDelta);
					spritePos.y = (currentNode.y * tileSize) + (((nextNode.y - currentNode.y) * tileSize) * lerpDelta);
				}

				this.sprite.x = spritePos.x;
				this.sprite.y = spritePos.y;
			} else {
				// check for new goal
				if (this.goalTileIndex != null) {
					this.path = this.aStar.findPath(this.tileIndex, this.goalTileIndex);
					this.currentNodeId = this.path.nodes.length;

					this.isWalking = true;
					this.sprite.animations.play('walk');

					this.goalTileIndex = null;
				}
			}
		}
	}
}