package com.phidgets
{
	import com.phidgets.events.PhidgetDataEvent;
	
	/*
		Class: PhidgetEncoder
	*/
	public class PhidgetEncoder extends Phidget
	{
		private var numEncoders:int = com.phidgets.Constants.PUNK_INT;
		private var numInputs:int = com.phidgets.Constants.PUNK_INT;
		private var inputs:Array = new Array(4);
		private var encoders:Array = new Array(4);
		
		public function PhidgetEncoder(){
			super("PhidgetEncoder");
			keyCountNeeded += 2;
		}
		
		override protected function onSpecificPhidgetDetach():void{
			numEncoders = com.phidgets.Constants.PUNK_INT;
			numInputs = com.phidgets.Constants.PUNK_INT;
			inputs = new Array(4);
			encoders = new Array(4);
		}
		
		override protected function onSpecificPhidgetData(setThing:String, index:int, value:String):void{
			switch(setThing)
			{
				case "NumberOfEncoders":
					numEncoders = int(value);
					keyCount++;
					break;
				case "NumberOfInputs":
					numInputs = int(value);
					keyCount++;
					break;
				case "Input":
					inputs[index] = value;
					if(isAttached)
						dispatchEvent(new PhidgetDataEvent(PhidgetDataEvent.INPUT_CHANGE,this,intToBool(inputs[index]),index));
					break;
				case "Position":
					var posnArray:Array = value.split("/");
					encoders[index] = posnArray[2];
					if(isAttached)
						dispatchEvent(new PhidgetDataEvent(PhidgetDataEvent.POSITION_CHANGE,this,int(encoders[index]),index));
					break;
				case "ResetPosition":
					encoders[index] = value;
					break;
			}
		}
		
		//Getters
		public function get InputCount():int{
			if(numInputs == com.phidgets.Constants.PUNK_INT)
				throw new PhidgetError(com.phidgets.Constants.EPHIDGET_UNKNOWNVAL);
			return numInputs;
		}
		public function get EncoderCount():int{
			if(numEncoders == com.phidgets.Constants.PUNK_INT)
				throw new PhidgetError(com.phidgets.Constants.EPHIDGET_UNKNOWNVAL);
			return numEncoders;
		}
		public function getPosition(index:int):int{
			return int(indexArray(encoders, index, numEncoders));
		}
		public function getInputState(index:int):Boolean{
			return intToBool(int(indexArray(inputs, index, numInputs)));
		}
		
		//Setters
		public function setPosition(index:int, val:int):void{ 
			_phidgetSocket.setKey(makeIndexedKey("ResetPosition", index, numEncoders), val.toString(), true);
		}
	}
}