import mx.remoting.debug.NetDebug;
import mx.remoting.PendingCall;
import mx.remoting.Service;
import mx.rpc.FaultEvent;
import mx.rpc.RelayResponder;
import mx.rpc.ResultEvent;

/**
 *  A Node handler for Spacelab website project
 *  - Call a node from drupal via amfphp
 *  
 *   
 *  * @author Petter
 */
 
class com.swededesigns.proj.spacelab.amfphp.Node {

  // The node id
  private var nid:Number;
  // The Node fields
  private var title:String = "";
  // The type of amfphp service
  private var service_type:String = "Node";
  // Node fields to fetch from dupal
  private var fields:Array = ["title"];
  // The gateway URL
  private var gatewayUrl:String;
  
  /**
   * Node Constructor
   *
   * @param   drupalUrl		The Url to your drupal install  
   * @param	  nodeId	   	The node id for the drupal node we want
   * 	                  
   */
   public function Node (drupalUrl:String, 
                          nodeId:Number) {
	trace("Node class: new node initiated");
    mx.events.EventDispatcher.initialize(this);
    nid = nodeId; 
	gatewayUrl = drupalUrl + "amfphp";
  }

	public function getData(): Void {
		trace("Node class: getData called");
		NetDebug.initialize();
		var _service:Service = new Service(gatewayUrl, null, service_type, null , null);
		var pc:PendingCall = _service.load(nid,fields);
		pc.responder = new RelayResponder(this, "handleResult", "handleError");
	}	
	
	private function handleResult(re:ResultEvent):Void{
		trace("Node class: handle result called");
		parseResult(re);
		this.dispatchEvent({type:"onLoad", target:this});
	}
	
	private function parseResult(re:ResultEvent):Void{
		trace("Node class: parse result called");
		var rs = re.result;
		title = rs["title"];	
	}	
	 
	private function handleError(fe:FaultEvent):Void{
		trace('Node class: There has been an error. The Node did not load because: ' + fe.fault.faultstring);
		this.dispatchEvent({type:"onLoadFail", target:this});
	}
	
	public function dispatchEvent(): Void {};
	public function addEventListener(): Void {};
	public function removeEventListener(): Void {};
	public function dispatchQueue(): Void {};
}