<?xml version="1.0" encoding="utf-8"?>
<!--
  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  - JaDOrT: JASMINe Deployment Orchestration Tool
  - Copyright (C) 2008-2009 Bull S.A.S.
  - Copyright (C) 2008-2009 France Telecom R&D
  - Contact: jasmine@ow2.org
  -
  - This library is free software; you can redistribute it and/or
  - modify it under the terms of the GNU Lesser General Public
  - License as published by the Free Software Foundation; either
  - version 2.1 of the License, or any later version.
  -
  - This library is distributed in the hope that it will be useful,
  - but WITHOUT ANY WARRANTY; without even the implied warranty of
  - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  - Lesser General Public License for more details.
  -
  - You should have received a copy of the GNU Lesser General Public
  - License along with this library; if not, write to the Free Software
  - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
  - USA
  -
  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  - $Id: UploadTopologyFile.mxml 3757 2009-05-27 08:37:14Z alitokmen $
  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-->
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
           cornerRadius="6"
           width="100%"
           height="100%"
           horizontalScrollPolicy="off"
           updateComplete="clearSelectionBoxes()"
           creationComplete="initApp()">

    <mx:Script>
        <![CDATA[

        import mx.controls.Alert;
        import mx.utils.ObjectUtil;
        import flash.events.*;
        import flash.net.FileReference;
        import flash.net.URLRequest;
        import org.ow2.jasmine.jadort.client.flex.model.*;
        import org.ow2.jasmine.jadort.client.flex.event.LoadTopologyEvent;
        import com.adobe.cairngorm.control.CairngormEventDispatcher;

        private var maxFileSize : Number = 4194304; //bytes;
        private var XMLTypes : FileFilter = new FileFilter("XML (*.xml)", ("*.xml"));
        private var allTypes : Array = new Array(XMLTypes);
        private const FILE_UPLOAD_URL : String = "./UploadFileServlet";
        private var fileRef : FileReference;

        [Bindable]
        public var model : JadortModelLocator = JadortModelLocator.getInstance();

        private function clearSelectionBoxes() : void {
            if (progressBar != null && btn_cancel != null) {
                progressBar.setProgress(0, 100);
                progressBar.label = "Click \"Browse\" and select the file to upload...";
                btn_cancel.enabled = false;
            }
        }

        private function initApp() : void {
             fileRef = new FileReference();
             fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
             fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, completeHandler);
             fileRef.addEventListener(Event.SELECT, selectHandler);
             fileRef.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
             fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
             fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
        }

        private function httpStatusHandler(event : HTTPStatusEvent) : void {
            if (event.status != 200)
            {
                var error : String = "Error " + event.status;
                if (event.status == 500) {
                    error = "Internal server error";
                }
                if (event.status == 404){
                    error = "File not found";
                }
                if (event.status == 415){
                    error = "File type not authorized";
                }
                if (event.status == 401){
                    error = "Access denied";
                }
                Alert.show(error, "HTTP error");
            }
        }

        private function securityErrorHandler(event : SecurityErrorEvent) : void {
            Alert.show(String(event), "Security error");
        }

        private function ioErrorHandler(event : IOErrorEvent) : void {
            Alert.show(String(event), "Input/Output error");
        }

        private function selectHandler(event : Event) : void {
            var msg : String ="";

            try {
                if (checkFileSize(fileRef.size)){
                    btn_upload.enabled = true;
                    progressBar.setProgress(0, 100);
                    progressBar.label = "File selected. Press \"Upload\" to upload it.";
                } else {
                    msg = fileRef.name + " is too large: " + Math.round(fileRef.size / 1024) + " Kb\n";
                    btn_upload.enabled = false;
                    Alert.show(msg + "Max file size is: " + Math.round(maxFileSize / 1024) + " Kb", "File Too Large",4,null);
                }
            } catch (error : Error) {
                btn_upload.enabled = false;
                Alert.show("File \"" + fileRef.name + "\" cannot be uploaded because it is an empty file.", "Upload Error");
            }
        }

        private function progressHandler(event : ProgressEvent) : void {
            progressBar.setProgress(event.bytesLoaded, event.bytesTotal);
        }

        private function completeHandler(event : DataEvent) : void {
            progressBar.label = "Complete.";
            btn_upload.enabled = false;
            btn_cancel.enabled = false;
            var dataXML:XML = XML(event.data.toString());
            var fileName : String = dataXML.file.attribute('name');
            if (dataXML != null || dataXML.length() <= 0 || fileName != null || fileName != "")
            {
                var loadTopologyEvent : LoadTopologyEvent = new LoadTopologyEvent(fileName);
                CairngormEventDispatcher.getInstance().dispatchEvent(loadTopologyEvent);
            } else {
                Alert.show("Problem uploading file. Check the server error log for details.");
            }
        }

        private function uploadFileFunction(theurl : String) : void {
            var req : URLRequest = new URLRequest;
            req.url = theurl;
            req.method = URLRequestMethod.POST;
 
            fileRef.upload(req);

            progressBar.label = "Uploading...";
            btn_cancel.enabled = true;
        }

        private function CancelFunction() : void {
            fileRef.cancel()
            clearSelectionBoxes();
        }

        // Checks the files do not exceed maxFileSize | if _maxFileSize == 0 No File Limit Set
        private function checkFileSize(filesize : Number) : Boolean {
            if (maxFileSize == 0){
                return (filesize <= maxFileSize);
            } else {
                return true;
            }
        }

        ]]>

    </mx:Script>
    <mx:Grid x="0" y="0" width="100%" height="100%" horizontalAlign="center">
        <mx:GridRow width="100%" height="30">
            <mx:GridItem width="220" height="100%" colSpan="2">
                <mx:Label width="100%" color="blue" text="Select a JaDOrT Server Topology XML file to upload:" height="100%" fontSize="11" />
            </mx:GridItem>
        </mx:GridRow>
        <mx:GridRow width="100%" height="30">
            <mx:GridItem width="220" height="100%">
                <mx:Label text="Select file and upload:" height="100%" width="100%" textAlign="right" />
            </mx:GridItem>
            <mx:GridItem width="100%" height="100%">
                <mx:FormItem direction="horizontal" >
                    <mx:Button width="80" label="Browse" click="fileRef.browse(allTypes)" />
                    <mx:Button width="80" label="Upload" id="btn_upload" enabled="false" click="uploadFileFunction(FILE_UPLOAD_URL)" />
                    <mx:Button width="80" label="Cancel" id="btn_cancel" enabled="false" click="CancelFunction()" />
                </mx:FormItem>
                </mx:GridItem>
        </mx:GridRow>
         <mx:GridRow width="100%" height="30">
             <mx:GridItem width="220" height="100%">
                 <mx:Label text="Progress:" height="100%" width="100%" textAlign="right" />
             </mx:GridItem>
             <mx:GridItem width="100%" height="100%">
                 <mx:ProgressBar id="progressBar" mode="manual" />
            </mx:GridItem>
         </mx:GridRow>
    </mx:Grid>
</mx:Canvas>
