package com.phidgets
{
	import flash.events.Event;
	import com.phidgets.events.PhidgetDictionaryEvent;
	import com.phidgets.events.PhidgetErrorEvent;
	import flash.events.EventDispatcher;
	
	/*
		Class: PhidgetDictionary
	*/
	public class PhidgetDictionary extends EventDispatcher
	{
		internal var _phidgetSocket:PhidgetSocket = null;
		
		private var calledClose:Boolean = false;

		public function openRemote(serverID:String, password:String = null):void {
			throw new PhidgetError(com.phidgets.Constants.EPHIDGET_UNSUPPORTED);
		}
		
		public function open(address:String, port:Number, password:String = null):void {
			_phidgetSocket = new PhidgetSocket();
			_phidgetSocket.connect(address, port, password, onConnected, onDisconnected, onError);
		}
		
		public function close():void {
			calledClose = true;
			_phidgetSocket.close();
		}
		
		private function onConnected():void {
			dispatchEvent(new PhidgetDictionaryEvent(PhidgetDictionaryEvent.CONNECT, this));
		}
		
		private function onDisconnected():void {
			if(!calledClose)
				dispatchEvent(new PhidgetDictionaryEvent(PhidgetDictionaryEvent.DISCONNECT, this));
			calledClose = false;
		}
		
		private function onError(error:PhidgetError):void {
			dispatchEvent(new PhidgetErrorEvent(PhidgetErrorEvent.ERROR,this,error));
		}
		
		public function addKey(key:String, value:String, persistent:Boolean=true):void {
			_phidgetSocket.setKey(key, value, persistent);
		}
		
		public function removeKey(pattern:String):void {
			_phidgetSocket.removeKey(pattern);
		}
		
		//From the socket
		public function get isConnected ():Boolean{
			return _phidgetSocket.isConnected;
		}
		public function get Address():String{
			if(_phidgetSocket.Address == null)
				throw new PhidgetError(com.phidgets.Constants.EPHIDGET_UNKNOWNVAL);
			return _phidgetSocket.Address;
		}
		public function get Port():int{
			if(_phidgetSocket.Port == com.phidgets.Constants.PUNK_INT)
				throw new PhidgetError(com.phidgets.Constants.EPHIDGET_UNKNOWNVAL);
			return _phidgetSocket.Port;
		}
		public function get ServerID():String{
			if(_phidgetSocket.ServerID == null)
				throw new PhidgetError(com.phidgets.Constants.EPHIDGET_UNKNOWNVAL);
			return _phidgetSocket.ServerID;
		}
	}
}