<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="730" height="355"
    creationComplete="init()" viewSourceURL="srcview/index.html">
    <mx:Style>
        .myTextInput {            
            backgroundColor : #e2e9eb;
            borderStyle : solid;
            borderColor:#334655;
            borderThickness:1;
            editable:true;
            color:#000000;
        }
    </mx:Style>
    <mx:Script>
        <![CDATA[
            import mx.rpc.AsyncToken;
            import flash.events.Event;
            import mx.controls.TextInput;
            import mx.events.DataGridEventReason;
            import mx.events.DataGridEvent;
            import mx.collections.ArrayCollection;
            import mx.controls.Alert;
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;
            import mx.rpc.remoting.RemoteObject;
            private var customersDataService:RemoteObject;
            
            private function init():void
            {
                customersDataService = new RemoteObject( "GenericDestination" );
                customersDataService.source = "Weborb.Examples.DataBinding";
                customersDataService.addEventListener( FaultEvent.FAULT, gotError );
                customersDataService.getCustomers.addEventListener( ResultEvent.RESULT, receivedCustomerRecords );
                customersDataService.updateCustomer.addEventListener( ResultEvent.RESULT, customerRecordUpdated );
                customersDataService.getCustomers();                
            }
            
            public function gotError( fault:FaultEvent ):void
            {
                Alert.show( "Server reported an error - " + fault.fault.faultString, "Error" ); 
            }
            
            public function receivedCustomerRecords( result:ResultEvent ):void
            {
                customersGrid.dataProvider = new ArrayCollection( result.result as Array );
            }
            
            public function customerRecordUpdated( result:ResultEvent ):void
            {
                mainPanel.status = "Record has been saved";
            }
            
            public function handleItemEditEnd( event:DataGridEvent ):void
            {
                var newData:String= TextInput( customersGrid.itemEditorInstance ).text;
                var oldData:String = customersGrid.dataProvider[ event.rowIndex ][ event.dataField ];
                
                if( event.dataField == "CustomerID" )
                {
                    mainPanel.status = "Cannot change customer ID";
                    event.preventDefault();
                    return;
                }
                
                if( newData == oldData )
                {
                    mainPanel.status = "Record not saved - no changes detected";                
                    return;
                }

                if( newData != "" )
                    handleUpdate( customersGrid.dataProvider[ event.rowIndex ], event.dataField, newData );
                
                if( event.reason == DataGridEventReason.OTHER || event.reason == DataGridEventReason.CANCELLED )
                {
                    //customersGrid.invalidateDisplayList();
                    event.preventDefault();
                    
                    if( newData != "" )
                    {
                        customersGrid.dataProvider[ event.rowIndex ][ event.dataField ] = newData;
                        customersGrid.invalidateList();
                    }
                        
                    return;
                }
                else if( newData == "" )
                {
                    mainPanel.status = "Cannot update with no data. Enter a valid string";
                    event.preventDefault();
                    TextInput(customersGrid.itemEditorInstance).errorString = "Enter a valid string.";
                    return;
                }
            }
            
            private function handleUpdate( updatedRowObject:Object, fieldName:String, newData:String ):void 
            {
                customersDataService.updateCustomer( updatedRowObject, fieldName, newData );
            }
            
            private function handleSelectionChange( event:Event ):void
            {
                var currentSelection:Object = customersGrid.selectedItem;
                customerID.text = currentSelection.CustomerID;
                contactName.text = currentSelection.ContactName;
                contactTitle.text = currentSelection.ContactTitle;
                companyName.text = currentSelection.CompanyName;
                address.text = currentSelection.Address;
                city.text = currentSelection.City;
                country.text = currentSelection.Country;
                postalCode.text = currentSelection.PostalCode;    
                updateButton.enabled = true;            
            }
            
            private function doUpdateWithForm( event:MouseEvent ):void
            {
                if( contactName.text.length == 0 ||
                contactTitle.text.length == 0 ||
                companyName.text.length == 0 ||
                address.text.length == 0 ||
                city.text.length == 0 ||
                country.text.length == 0 ||
                postalCode.text.length == 0 )
                {
                    Alert.show( "All fields are required", "Incomplete Form" );
                    return;
                }
                
                var updateObject:Object = new Object();
                updateObject.CustomerID = customerID.text;
                updateObject.ContactName = contactName.text;
                updateObject.ContactTitle = contactTitle.text;
                updateObject.CompanyName = companyName.text;
                updateObject.Address = address.text;
                updateObject.City = city.text;
                updateObject.Country = country.text;
                updateObject.PostalCode = postalCode.text;
                var asyncToken:AsyncToken = customersDataService.updateCustomer( updateObject );
                
                asyncToken.addResponder( new mx.rpc.Responder(
                    function( event:ResultEvent ):void
                    {
                        customersGrid.dataProvider[ customersGrid.selectedIndex ] = updateObject;
                        Alert.show( "Record has been saved", "Success" );
                    },
                    function( fault:FaultEvent):void
                    {
                        gotError( fault );
                    }
                ));    
            }
        ]]>
    </mx:Script>
    <mx:Panel x="10" y="10" width="710" height="335" layout="absolute" title="Flex DataGrid Data Binding using Remoting" id="mainPanel">
        <mx:DataGrid 
            x="0" y="0" width="690" height="146" 
            id="customersGrid" editable="true" 
            itemEditEnd="handleItemEditEnd(event)"
            change="handleSelectionChange(event)">
            <mx:columns>
                <mx:DataGridColumn headerText="Customer ID" dataField="CustomerID" backgroundColor="0xe2e9eb" />
                <mx:DataGridColumn headerText="Contact Name" dataField="ContactName" />
                <mx:DataGridColumn headerText="Contact Title" dataField="ContactTitle" />
                <mx:DataGridColumn headerText="Company Name" dataField="CompanyName" />
                <mx:DataGridColumn headerText="Address" dataField="Address" />
                <mx:DataGridColumn headerText="City" dataField="City" />
                <mx:DataGridColumn headerText="Country" dataField="Country" />
                <mx:DataGridColumn headerText="PostalCode" dataField="PostalCode" />                
            </mx:columns>
        </mx:DataGrid>
        <mx:Canvas x="10" y="158" width="670" height="129" borderStyle="solid" cornerRadius="10">
            <mx:Text x="68" y="17" text="Customer ID:"/>
            <mx:Text x="68" y="43" text="Contact Name:"/>
            <mx:Text x="68" y="69" text="Contact Title:"/>
            <mx:Text x="68" y="95" text="Company Name:"/>
            <mx:TextInput styleName="myTextInput" x="170" y="41" width="131" id="contactName"/>
            <mx:TextInput x="170" y="15" width="131" backgroundColor="#ffffff" borderStyle="none" borderThickness="1" editable="true" color="#000000" fontWeight="bold" id="customerID"/>
            <mx:TextInput styleName="myTextInput" x="170" y="67" width="131" id="contactTitle"/>
            <mx:TextInput styleName="myTextInput" x="170" y="95" width="131" id="companyName"/>
            <mx:Text x="343" y="17" text="Address:"/>
            <mx:Text x="343" y="43" text="City:"/>
            <mx:Text x="343" y="69" text="Country:"/>
            <mx:Text x="343" y="95" text="Postal Code:"/>
            <mx:TextInput styleName="myTextInput" x="428" y="41" width="131" id="city"/>
            <mx:TextInput styleName="myTextInput" x="428" y="15" width="131" id="address"/>
            <mx:TextInput styleName="myTextInput" x="428" y="67" width="131" id="country"/>
            <mx:TextInput styleName="myTextInput" x="428" y="95" width="131" id="postalCode"/>
            <mx:Button x="591" y="95" label="Update" id="updateButton" enabled="false" click="doUpdateWithForm(event)"/>
        </mx:Canvas>
        <mx:Text x="22" y="150" text="Update Selected Row" opaqueBackground="0xffffff" fontWeight="bold"/>
    </mx:Panel>
    
</mx:Application>