<?xml version="1.0" encoding="utf-8"?>
<!-- 
Copyright (c) 2010 http://www.immanuelnoel.com

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->

<!--
    The Component retreives data from a HTTP GET WebService, 
    Inserts the data into a local SQLite Database,
    and Pop's up another component to show the data last inserted into the database.

    The component also shows the records existing in the database
-->

<s:BorderContainer xmlns:fx="http://ns.adobe.com/mxml/2009" 
                   xmlns:s="library://ns.adobe.com/flex/spark" 
                   xmlns:mx="library://ns.adobe.com/flex/mx" width="100%" height="100%" backgroundAlpha="0.0" backgroundColor="#A20000">
    <s:layout>
        <s:VerticalLayout horizontalAlign="center" verticalAlign="middle"/>
    </s:layout>
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
        <s:HTTPService id="hsData" method="GET" 
                       url="http://code.immanuelnoel.com/Services/HelloWorld.php?getData=1" 
                       result="hsData_resultHandler(event)" 
                       fault="hsData_faultHandler(event)"/>
    </fx:Declarations>
    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.managers.PopUpManager;
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;
            
            [Bindable]protected var sample:ArrayCollection = new ArrayCollection();
            protected var sampleDB:SQLConnection;
            
            /** Call the REST Webservice on clicking the 'Get Data' button
             */
            protected function btGetData_clickHandler(event:MouseEvent):void
            {
                cursorManager.setBusyCursor();
                hsData.send();
            }

            /** Event Listener for handling the result obtained from the Webservice
             */
            protected function hsData_resultHandler(event:ResultEvent):void
            {
                insertIntoDatabase(String(event.result.data.testData));
            }
            
            /** Event Listener for handling errors while calling the Webservice
             */
            protected function hsData_faultHandler(event:FaultEvent):void
            {
                cursorManager.removeAllCursors();
                lStatus.text = "Oops! Connectivity Error";
            }
            
            /** Method to insert data retreived from the Webservice, into the SQLite Database
             */
            private function insertIntoDatabase(data:String):void
            {
                lStatus.text = "Inserting into database. Please Wait...";
                
                /** Specifying the location of the SQLite File, and 
                 *     creating a new SQL Connection
                 */
                var dbFile:File = File.applicationDirectory.resolvePath("Example4_Files/test.sqlite");
                sampleDB = new SQLConnection();
                
                /** Adding a event listener for the Database Open Event,
                 *     and writing an inline function.
                 * 
                 *  The fault event for opening the database is not handled in this case !
                 */
                sampleDB.addEventListener(SQLEvent.OPEN, function():void
                {
                    var stmt1:SQLStatement = new SQLStatement();
                    stmt1.sqlConnection = sampleDB;
                    stmt1.text = "INSERT INTO sampletable(sampleData) values('"+data+"')";
                    
                    /** Adding a event listener for the catching result of the execution of SQL Statement,
                     *  along with an inline function.
                     */
                    stmt1.addEventListener(SQLEvent.RESULT, function():void
                    {
                        lStatus.text = "Retrieving from Database. Please Wait...";
                        getDataFromDB();
                    });
                    
                    /** Adding a event listener for the catching errors in the execution of SQL Statement,
                     *  along with an inline function.
                     */
                    stmt1.addEventListener(SQLErrorEvent.ERROR, function():void
                    {
                        cursorManager.removeAllCursors();
                        lStatus.text = "Error in inserting into Database";
                    });
                    
                    stmt1.execute();
                });
                
                sampleDB.open(dbFile);
            }
            
            /** Method to retreive data from the SQLite Database
             */
            private function getDataFromDB():void
            {
                // FETCH DATA FROM DATABASE
                
                lStatus.text = "Fetching data from the Database. Please Wait...";
                
                var stmt2:SQLStatement = new SQLStatement();
                stmt2.sqlConnection = sampleDB;
                
                stmt2.text = "SELECT * from sampletable ORDER BY sampleDataID DESC LIMIT 0, 1";
                
                stmt2.addEventListener(SQLEvent.RESULT, function():void
                {
                    /** Reading data returned from the execution of the SQL Statement
                     */
                    
                    sample = new ArrayCollection(stmt2.getResult().data);
                    
                    sampleDB.close();
                    
                    displayPopUp(String(sample[0].sampleData));
                });
                
                stmt2.addEventListener(SQLErrorEvent.ERROR, function():void
                {
                    cursorManager.removeAllCursors();
                    lStatus.text = "Error in retreiving from Database";
                });
                
                stmt2.execute();
            }
            
            /** Displaying a PopUp, and updating the label in the PopUp 
             *     with the value fetched from the Database
             */
            private function displayPopUp(data:String):void
            {
                var popup:Example4_PopUp = PopUpManager.createPopUp(this, Example4_PopUp, true) as Example4_PopUp;
                PopUpManager.centerPopUp(popup);
                popup.lDisplay.text = data;
                cursorManager.removeAllCursors();
                lStatus.text = "";
            }
            
            /** Displaying a PopUp to show contents of the Database
             */
            protected function btGetDBData_clickHandler(event:MouseEvent):void
            {
                var popup:Example4_DBData = PopUpManager.createPopUp(this, Example4_DBData, true) as Example4_DBData;
                PopUpManager.centerPopUp(popup);
                cursorManager.removeAllCursors();
                lStatus.text = "";
            }

        ]]>
    </fx:Script>
    <s:Label id="lDisplay" text="Demonstrates connecting to a WebService and SQLite DB" color="#FFFFFF" fontFamily="Verdana" fontSize="14"/>
    <s:Label id="lStatus" text="Click the button below to continue" color="#FFBA00" fontFamily="Verdana"/>
    <s:HGroup>
        <s:Button id="btGetData" label="Click Me !" click="btGetData_clickHandler(event)"/>
        <s:Button id="btGetDBData" label="View DB" click="btGetDBData_clickHandler(event)"/>
    </s:HGroup>
</s:BorderContainer>