<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationCompleteHandler()" viewSourceURL="assets/pages/srcview/PrintDataExample/index.html">

    <!-- add Yahoo! Flex styles (http://developer.yahoo.com/flash/articles/yahoo-flex-skin.html) -->
    <mx:Style source="assets/styles/yflexskin.css" />

    <!-- load sample data -->
    <mx:Model id="contactsData" source="data/contacts.xml" />

    <mx:Script>
        <![CDATA[
            import mx.events.CloseEvent;
            import mx.controls.Alert;
            import mx.rpc.events.ResultEvent;
            import mx.rpc.events.FaultEvent;
            import mx.collections.ArrayCollection;
            
            [Bindable]
            private var contacts:ArrayCollection;
            
            [Bindable]
            private var printOptions:Array =     [    {data: 'inline',     label: 'Display in Browser'},
                                                    {data: 'attachment', label: 'Save/Open from Browser'},
                                                    {data: 'fromFlash', label: 'Save from Flash Player 10'}];
            private var pdfData:ByteArray;                                        
                                                    
            
            private function creationCompleteHandler():void{
                contacts = new ArrayCollection(contactsData.contact);
            }//end creationCompleteHandler function
            
            private function doPrint():void{
                //make server call to get PDF data
                cfService.printSampleData({    printTitle: 'Contact data for Your Company',
                                            dataToPrint: contacts,
                                            printLetterhead: includeHeaderOptions.selectedValue});
            }//end doPrint function
            
            private function resultHandler(event:ResultEvent):void{
                pdfData = event.result as ByteArray;
                switch(printOptionsCb.selectedItem.data){
                    case "fromFlash":
                        var player:Array = getPlayerVersion();
                        if(player[0] < 10){
                            Alert.show("You must have Flash Player version 10 or higher. " + player[0]);
                            return;                        
                        }
                        /* we cannot call the savePDF() method directly from here because user interaction is
                           required to use the FileReference.save() method.  As a work-around we will prompt for permission */
                        Alert.show("Permit system access to save this file?", "Confirmation", Alert.OK |Alert.CANCEL, null, confirmationHandler);
                        break;
                    case "attachment":
                        generatePDF(pdfData, 'attachment');
                        break;
                    default:
                        generatePDF(pdfData, 'inline');
                }
            }//end resultHandler function
            
            private function faultHandler(event:FaultEvent):void{
                Alert.show("There was a problem connecting to the server", "ERROR");
            }//end faultHandler function
            
            private function confirmationHandler(event:CloseEvent):void{
                //if the user clicked Ok on the confirmation dialog
                if(event.detail == 4)
                    savePDF(pdfData);
            }//end confirmationHandler function
            
            private function savePDF(pdfBinary:ByteArray):void{
                var fileRef:FileReference = new FileReference();
                fileRef.save(pdfBinary, "yourPrintout.pdf");
            }//end savePDF function
            
            private function generatePDF(pdfBinary:ByteArray, method:String):void{
                //result comes back as binary, create a new URL request and pass it back to the server
                var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
                var urlString:String = "http://kalengibbons.com/assets/pages/pdfCreator.cfm";
                if(method == "inline")
                    urlString += "?method=inline";
                else
                    urlString += "?method=attachment&name=dataPrintSample.pdf";
                var sendRequest:URLRequest = new URLRequest(urlString);
                sendRequest.requestHeaders.push(header);
                sendRequest.method = URLRequestMethod.POST;
                sendRequest.data = pdfBinary;
                navigateToURL(sendRequest, "_blank");
            }//end generatePDF function
            
            private function getPlayerVersion():Array{
                var playerDetails:String = Capabilities.version;
                var osDetails:Array = playerDetails.split(' ');
                return osDetails[1].split(',');
            }//end getPlayerVersion function
            
        ]]>
    </mx:Script>
    
    <mx:RemoteObject id="cfService"
        destination="ColdFusion"
        endpoint="/flex2gateway/"
        showBusyCursor="true" 
        source="cfc.printData"
        result="resultHandler(event)"
        fault="faultHandler(event)" />
    
    <mx:Panel title="Printing Data to PDF" id="mainPanel" height="100%" width="100%" verticalGap="10">
        <mx:HBox width="100%" verticalAlign="middle">
            <mx:Label text="Print Options:" fontWeight="bold" />
            <mx:ComboBox id="printOptionsCb" dataProvider="{printOptions}" labelField="label" />
            <mx:Spacer width="50" />
            <mx:Label text="Include Header:" fontWeight="bold" />
            <mx:RadioButtonGroup id="includeHeaderOptions" />
            <mx:RadioButton groupName="includeHeaderOptions" value="true" label="Yes" />
            <mx:RadioButton groupName="includeHeaderOptions" value="false" label="No" selected="true" />
            <mx:Spacer width="50" />
            <mx:Button label="Print Data" click="doPrint()" />
        </mx:HBox>
        <mx:DataGrid width="100%" height="100%" dataProvider="{contacts}" />
    </mx:Panel>
        
    
</mx:Application>