<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" viewSourceURL="srcview/index.html">
    <mx:HTTPService 
        id="RESTService" 
        url="json.jsp" 
        resultFormat="text"
        result="onLoadTweetsResult(event)"
        fault="onLoadTweetsFault(event)"
        showBusyCursor="true">
    </mx:HTTPService>
    
    <mx:Script>
        <![CDATA[
            import mx.controls.dataGridClasses.DataGridColumn;
            import mx.messaging.AbstractConsumer;
            import mx.rpc.events.ResultEvent;
            import mx.rpc.events.FaultEvent;
            import mx.collections.ArrayCollection;
            import com.adobe.serialization.json.JSON;
            
            [Bindable]
            private var tweets:ArrayCollection;
            
            private function loadTweets():void {
                RESTService.send();
            }
            
            private function onLoadTweetsResult(event:ResultEvent):void {
                var rawJSON:String = String(event.result);
                var arrayJSON:Array = JSON.decode(rawJSON) as Array;
                tweets = new ArrayCollection(arrayJSON);
            }
            
            private function onLoadTweetsFault(event:FaultEvent):void {
                trace(event.fault.toString());
            }
            
            private function getScreenName(tweet:Object, column:DataGridColumn):String {
                return tweet.user.screen_name;
            }
            
            private function getName(tweet:Object, column:DataGridColumn):String {
                return tweet.user.name;
            }            
        ]]>
    </mx:Script>
    
    <mx:VBox width="100%" height="50%" paddingBottom="60" paddingLeft="60" paddingRight="60" paddingTop="60">
        <mx:Label text="RESTful Flex/Flash client (jose@josesandoval.com)" fontSize="24" fontWeight="bold" />
        
        <mx:DataGrid dataProvider="{tweets}" width="100%" rowCount="12">
            <mx:columns>
                <mx:DataGridColumn width="200" headerText="Screen Name" labelFunction="getScreenName" />
                <mx:DataGridColumn width="200" headerText="Name" labelFunction="getName" />
                <mx:DataGridColumn headerText="Tweet" dataField="text" />
            </mx:columns>
        </mx:DataGrid>                    
        
        <mx:Button label="Get Tweets" click="{RESTService.send()}" />
    </mx:VBox>        
</mx:Application>