/* #1 - Update package for your project */
package net.halcyonsolutions.cairngormchallenge.command
{
	import mx.rpc.IResponder;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import net.halcyonsolutions.cairngormchallenge.delegate.ProductDelegate;
	import net.halcyonsolutions.cairngormchallenge.model.ApplicationModel;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.events.FaultEvent;
	import mx.controls.Alert;
	import mx.collections.ICollectionView;
	import mx.collections.Sort;
	import mx.collections.SortField;
	import mx.utils.ArrayUtil;
	import mx.collections.ArrayCollection;
	/* #2 - Import VOs to be used */
	
	/**
	 * 
	 */
	/* #3 - Name class accordingly */
	public class GetProductsCommand implements ICommand, IResponder
	{
		private static var model:ApplicationModel = ApplicationModel.getInstance();

	  	/* #4 - [Optional] Constructor.  Must match your class name */
	  	public function GetProductsCommand()
		{	 
			// empty constructor
		}
	
		public function execute( event : CairngormEvent ): void
		{

			/* #5 - Logic to test if data exists yet in the model */
			if( model.products.length == 0 ) 
			{
			    var delegate : ProductDelegate = new ProductDelegate( this );
			    delegate.getProducts();
			}
			else
			{
				Alert.show( "Products already retrieved!" );
				return;
			}
		}
	
		public function result( event : Object ) : void
		{		
				
			/* #6 - Best practice is, wherever possible, only Commands set data on the model.
			        Add your logic here.
			*/
			var result:ResultEvent = event as ResultEvent;
			
			model.products = ArrayCollection(result.result.products.product);
			
		}
	
		public function fault( event : Object ) : void
		{
			/* #7 - [Optional] Customize error handling as required  */
			var faultEvent : FaultEvent = FaultEvent( event );
			Alert.show( "Products could not be retrieved!" );
		}
	}

}