"use strict";
var powerUpsHandler = function() {
	var board;
	var startDualPoints;
	var shieldPtr;
	var msgPtr;
	var doublePtr;
	var getBySpriteType = function(type, zIndex) {
		board = game.getBoard();
		for ( var k = 0; k < board.objects[zIndex].length; k++) {
			if (board.objects[zIndex][k].type === type) {
				return board.objects[zIndex][k];
			}
		}
		return false;
	}

	return {
		points : 1,

		updateDoublePointsStartTime : function(time) {
			if (startDualPoints) {
				startDualPoints = new Date((startDualPoints.getTime() + time));
				game.log("updated + " + time);
			}
		},

		killAllEnemies : function() {
			board = game.getBoard();
			for ( var k = 0; k < board.objects[config.enemy.zIndex].length; k++) {
				if (board.objects[config.enemy.zIndex][k].type === game.getObjectTypes().ENEMY) {
					board.objects[config.enemy.zIndex][k].hit(1000);
				}
			}
		},

		repairPlayer : function() {
			var player = getBySpriteType(game.getObjectTypes().PLAYER, config.player.zIndex);
			if (player) {
				player.repair();
			}
		},

		healEarth : function() {
			var earth = getBySpriteType(game.getObjectTypes().EARTH, config.earth.zIndex);
			if (earth) {
				earth.heal();
			}
		},

		doublePoints : function() {
			this.updateDoublePointsStartTime(1000 * config.powerUps.dualPointsTime);
			if (startDualPoints)
				return false;
			startDualPoints = new Date();
			board = game.getBoard();
			messageBoxManager.show(new MessageBox("Double points for " + config.powerUps.dualPointsTime + " sec"));
			this.points = 2;
			var endDouble = function() {
				var now = new Date();
				if (!game.isPaused() && (now.getTime() - startDualPoints.getTime()) > config.powerUps.dualPointsTime * 1000) {
					this.points = 1;
					messageBoxManager.show(new MessageBox("Double points time finished!"));
					startDualPoints = null;
				} else
					doublePtr = setTimeout(endDouble, 1000);
			};
			endDouble();
		},

		shield : function() {
			var player = getBySpriteType(game.getObjectTypes().PLAYER, config.player.zIndex);
			if (player.hasShield()) {
				messageBoxManager.show(new MessageBox("Shield time extended"), 2000);
				clearTimeout(shieldPtr);
				clearTimeout(msgPtr);
			}
			player.setShield(true);
			shieldPtr = setTimeout(function() {
				messageBoxManager.show(new MessageBox("Shield will be removed in 3 sec"), 3000);
				msgPtr = setTimeout(function() {
					player.setShield(false);
				}, 3000);
			}, (config.powerUps.shieldTime - 5) * 1000);
		},

		/**
		 * Resets all power ups
		 * 
		 * @returns
		 */
		reset : function() {
			var player = getBySpriteType(game.getObjectTypes().PLAYER, config.player.zIndex);
			player.setShield(false);
			this.points = 1;
		}
	};
}();