"use strict";

/* A formation pattern in the shape of a circle */
function LinePattern(charRadius) {
	this.characterRadius = (charRadius) ? charRadius : 25;
	this.numberOfSlots = 0;
}

/* Loops through a list of characters assigned to slots and finds the number of slots in the formation */
LinePattern.prototype.calculateNumberOfSlots = function(assignments) {
	var maxSlotNumber = -1;
	
	for(var i = 0; i < assignments.length; i++) {
		if(assignments[i].slotNumber > maxSlotNumber) {
			maxSlotNumber = assignments[i].slotNumber;
		}
	}
	
	/* Number of slots is 1 plus the maxSlotNumber (since slot numbers start at 0) */
	this.numberOfSlots = maxSlotNumber+1;
	
	/* If the max number of slots is less than the number of assignments then use the number of assignments as the number of slots */
	if(this.numberOfSlots < assignments.length) {
		this.numberOfSlots = assignments.length;
	}
	
	return this.numberOfSlots;
};

/* Gets the slot cost for given character at the given slot */
LinePattern.prototype.getSlotCost = function(slotNumber, character) {
	/* Get the role type of the slot depending on whether the slot number is even or odd */
	var role = (slotNumber % 2 === 0) ? 1 : 2;
	
	return character.getSlotCost(role);
};


/* Calculates the center of mass of the assignments */
LinePattern.prototype.getCenterOfMass = function(assignments) {
	/* Update the numberOfSlots before we start in case something has changed */
	this.calculateNumberOfSlots(assignments);

	/* Get the center of mass of the assigned characters in their slots */
	var center = new GameObject();
	
	for(var i = 0; i < assignments.length; i++) {
		var location = this.getSlotLocation(assignments[i].slotNumber);
		vec3.add(center.position, center.position, location.position);
		center.orientation += location.orientation;
	}
	
	vec3.scale(center.position, center.position, 1/assignments.length);
	center.orientation /= assignments.length;
	
	return center;
};

/* Gets the relative location of the given slot number */
LinePattern.prototype.getSlotLocation = function(slotNumber) {
	/* If the formation has no slots in use then return a default game object
	   or if there is one slot in use then also return a default game object 
	   since that is the correct result for 1 slot */
	if(this.numberOfSlots <= 1) {
		return new GameObject();
	}
	
	var x  = (slotNumber * 2 * this.characterRadius) - (2 * this.characterRadius * this.numberOfSlots)/2 + this.characterRadius;
	
	var location = new GameObject([0,0,0], 0);
	location.position[0] = x;
	location.position[2] = 50;
	
	
	
	location.orientation = 0;
	
	return location;
};

/* Determines if the pattern can support the number of slots */
LinePattern.prototype.supportsSlots = function(slotCount) {
	return (slotCount > 0);
}