/* UnitCollection.js
 * An object that wraps a Unit or an Array of Units so that they may be treated the same
 * e.g., UnitCollection.setState({my:state}) will loop through all Units in its collection and set the state.
 */

BLIP.Class.create("BLIP.UnitCollection", BLIP.Object,
	function(unitArray) {
		this.units = [];
		if (unitArray && unitArray.length > 0) {
			this.units = unitArray;
		}
		else if (unitArray) {
			this.units.push(unitArray);
		}
	},

	{
		each : function(fn) {
			for (var i = 0, len = this.units.length; i < len; i++) {
				fn(this.units[i]);
			}
		},

		push : function (unit) {
			if (unit) {
				this.units.push(unit);
			}
		},

		length : function() {
			return this.units.length;
		},

		getSingleState : function(i) {
			i = i || 0;
			return this.units[i].getState();
		},

		getMultipleStates : function() {
			var state = [],
					i;

			for (i = 0, len = this.units.length; i < len; i++) {
				state.push(this.getSingleState(i));
			}

			return state;
		},

		getState : function () {
			var state;
			if (this.units.length === 1) {
				state = this.getSingleState();
			}
			else {
				state = this.getMultipleStates();
			}
			return state;
		},


		setIdenticalStateOnAllUnits : function(state) {
			for (var i = 0, len = this.units.length; i < len; i++) {
				this.units[i].setState(state);
			}
		},

		setMultipleStatesOnMultipleUnits : function(states) {
			if (states.length !== this.units.length) {
				throw new TypeError("Wrong number of states to set on collected units");
			}

			for (var i = 0, len = states.length; i < len; i++) {
				this.units[i].setState(states[i]);
			}
		},

		setState : function (state) {
			if(state.constructor === Array) {
				this.setMultipleStatesOnMultipleUnits(state);
			}
			else {
				this.setIdenticalStateOnAllUnits(state);
			}
		},

		single : function (n) {
			n = n || 0;
			return this.units[n];
		}
	}
);

