<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
                implements="mx.rpc.IResponder" 
                creationComplete="onCreationComplete()" 
                backgroundGradientColors="[#ffffff,#ffffff]" 
                layout="absolute" viewSourceURL="srcview/index.html">
<!--
    FlexFaceOnAlfresco Demo Application
    Author: Jim Robson jim@robsondesign.com 
    
    This application shows how a Flex user interface can integrate with an Alfresco
    repository. It is not intended to show good Flex design or architecture; for 
    more information on architecting extensible, scalable, and maintainable Flex
    applications, please feel free to contact me at the address above. 
-->
    <mx:Script>
        <![CDATA[
            import com.eyestreet.flex.ui.admin.LoginPanel;
            import com.eyestreet.flex.events.admin.LoginAttemptEvent;
            
            import mx.collections.XMLListCollection;
            import mx.managers.PopUpManager;
            import mx.rpc.AsyncToken;
            import mx.rpc.http.mxml.HTTPService;
            import mx.rpc.IResponder;
            
            import org.alfresco.framework.service.authentication.*;
            import org.alfresco.framework.service.error.*;
            
            // Collection of Action Items
            [Bindable]
            public var actionItemsCollection:XMLListCollection;
            
            
            // Handles HTTP Responses
            public function result(data:Object):void
            {
                var xml:XML = XML(data.message.body);
                var list:XMLList = XMLList(xml.actionItem);
                actionItemsCollection = new XMLListCollection(list);
            }
            // Handles RPC faults
            public function fault(fault:Object):void
            {
                trace(fault.fault.faultString);
            }
            
            // Alfresco session ticket
            private var _alfTicket:String;
            
            // Login Panel component
            private var _loginPanel:LoginPanel;
            
            // Alfresco Flex SDK Classes 
            private var _authenticationService:AuthenticationService = AuthenticationService.instance;
            private var _errorService:ErrorService = ErrorService.instance;
            
            // Handles the creationComplete event for the application object
            private function onCreationComplete():void
            {
                // Display the login form
                showLoginPanel();
                // Listen for Alfresco Flex SDK events
                _authenticationService.addEventListener(LoginCompleteEvent.LOGIN_COMPLETE, onLoginComplete);
                _errorService.addEventListener(ErrorRaisedEvent.ERROR_RAISED, onLoginError);
            }
            
            // Displays the login form
            private function showLoginPanel():void
            {
                // Create the login form
                _loginPanel = PopUpManager.createPopUp(this, LoginPanel, true) as LoginPanel;
                // Listen for login attempt events (dispatched when the user attempts to login)
                _loginPanel.addEventListener(LoginAttemptEvent.LOGIN_ATTEMPT, onLoginAttempt);
                // Center the form in the screen
                PopUpManager.centerPopUp(_loginPanel);
            }
            
            // Handles login attempt events (dispatched when the user attempts to login)
            // This method should work with any Alfresco installation as long as the
            // paramters in alfresco-config.xml are set correctly. It leverages
            // the Alfresco Flex SDK
            private function onLoginAttempt(event:LoginAttemptEvent):void
            {
                // Get the userName and password
                var userName:String = event.userName;
                var password:String = event.password;
                // Pass the userName and password to Alfresco's
                // authentication api
                _authenticationService.login(userName, password);
            }
            
            // Handles successful login events
            private function onLoginComplete(event:LoginCompleteEvent):void
            {
                // Store the Alfresco session ticket
                _alfTicket = event.ticket;
                // Remove the login form
                hideLoginPanel();
                // Fetch some data to display
                loadActionItems();
            }
            
            // Handles unsuccessful login attempts
            private function onLoginError(event:ErrorRaisedEvent):void
            {
                // Get information about the error
                var loginErrorMessage:String = event.errorType + "\n";
                loginErrorMessage += event.error.message + ":\n" ;
                loginErrorMessage += event.error.getStackTrace();
                // Display the error info in the login form
                _loginPanel.loginFailed(loginErrorMessage);
            }
            
            // Removes the login form
            private function hideLoginPanel():void
            {
                // Remove event listeners so the object can be garbage collected
                _loginPanel.removeEventListener(LoginAttemptEvent.LOGIN_ATTEMPT, onLoginAttempt);
                // Remove the form from the screen
                PopUpManager.removePopUp(_loginPanel);
                // Make sure that it's ready for garbage collection
                _loginPanel = null;
            }
            
            // Fetches a list of action items from the repository. 
            // Assumes a custom webScript method called getActionItems
            // that returns an XML response. Provides an example of 
            // interacting with Alfresco without the Alfresco Flex SDK. 
            private function loadActionItems():void
            {
                // Create an object to hold request parameters
                var params:Object = new Object;
                // At minimum, you'll need to send the Alfresco ticket
                // Depending on your implementation, you are likely to need
                // some additional parameters as well
                params.alf_ticket = _alfTicket;
                var service:HTTPService = new HTTPService;
                // In a real situation, your URL would probably look something
                // like this...
                //        service.url = "http://localhost:8080/alfresco/service/getActionItems";
                // However, for that to work, you would need to have a webScript
                // with a getActionItems method that returns XML. Meanwhile, feel free
                // to use this static XML file...
                service.url = "data/actionItems.xml";
                // Assign the method (e.g. POST, GET)
                service.method = "GET";
                // Send the request to the server
                var token:AsyncToken = service.send(params);
                // Make sure that this application object gets the server's response
                // (See the result and fault methods above)
                token.addResponder(this);
            }
            
            
        ]]>
    </mx:Script>
    
    <mx:Image id="appLogo" source="assets/AlfrescoPlusFlex.png" y="21" horizontalCenter="0" />
    <!-- DataGrid to display the list of Action Items returned from the server -->
    <mx:DataGrid id="actionItemsGrid" dataProvider="{actionItemsCollection}" top="170" right="20" bottom="10" left="20">
        <mx:columns>
            <mx:DataGridColumn dataField="priority" headerText="Priority" />
            <mx:DataGridColumn dataField="description" headerText="Description" />
            <mx:DataGridColumn dataField="issueDate" headerText="Issued" />
            <mx:DataGridColumn dataField="dueDate" headerText="Due" />
        </mx:columns>
    </mx:DataGrid>
    
</mx:Application>