package flater.cairngormtips.controller.delegates
{
import com.universalmind.cairngorm.business.Delegate;
import com.universalmind.cairngorm.events.Callbacks;

import flater.cairngormtips.util.out;

import mx.rpc.AsyncToken;
import mx.rpc.IResponder;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.mxml.HTTPService;

/**
 *  A delegate for performing the getItems operation for the
 *  <code>DataTranslatorExampleApplication</code><br/> 
 *  <br/>                                                                                            
 *  Author: <a href="http://www.adamflater.net" target="_blank">
 *  Adam Flater</a>
 *  <br/>
 *                                                                                           
 *  @see flater.cairngormtips.controller.commands.ItemsCommand
 *  @see flater.cairngormtips.DataTranslatorExampleApplication
 */ 
public class DataTranslatorExampleDelegate extends Delegate
{
    
    public function DataTranslatorExampleDelegate(
                          commandHandlers : IResponder = null )
    {
        super( commandHandlers, "itemsService" );

        out( "DataTranslatorExampleDelegate Instantiated" );
    }
    
    //--------------------------------------
    //  getItems
    //--------------------------------------
    
    /**
     *  Downloads the config xml data for the application
     */
    public function getItems() : void
    {
        out( "DataTranslatorExampleDelegate.getItems() invoked" );

        var token : AsyncToken = (service as HTTPService).send();
        
        prepareHandlers( token, new Callbacks( getItems_Result, 
                                               getItems_Fault ) );
    }
    
    /**
     *  @private
     * 
     *  Event handler; Responds to the results of the getItems 
     *  operation.
     */
    private function getItems_Result( info : Object ) : void
    {
        out( "DataTranslatorExampleDelegate.getItems_Result() " + 
             "invoked" );

       var xml     : XML    = ( info as ResultEvent ).result as XML;
       var items   : Array  = 
           ExampleDataTranslator.ParseItems( xml.item );
       
       responder.result( items );    
    }
    
    /**
     *  @private
     * 
     *  Event handler; Responds to the faults of the getItems 
     *  operation.
     */
    private function getItems_Fault( info : Object ) : void
    {
        out( "DataTranslatorExampleDelegate.getItems_Fault() " + 
             "invoked" );

        responder.fault( info );    
    }
    
    
} //  end class
} //  end package