<?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: Index.mxml 3732 2009-05-19 19:38:04Z alitokmen $
  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
                xmlns:view="org.ow2.jasmine.jadort.client.flex.view.*"
                xmlns:business="org.ow2.jasmine.jadort.client.flex.business.*"
                xmlns:control="org.ow2.jasmine.jadort.client.flex.control.*"
                layout="absolute"
                paddingLeft="10"
                paddingBottom="10"
                paddingRight="10"
                paddingTop="10"
                verticalAlign="top"
                creationComplete="init()">

    <mx:Style source="JaDOrT.css" />
    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.controls.Alert;

            import flash.utils.Timer;
            import flash.events.TimerEvent;
            import org.ow2.jasmine.jadort.client.flex.model.JadortModelLocator;
            import org.ow2.jasmine.jadort.client.flex.event.*;
            import org.ow2.jasmine.jadort.client.flex.vo.*;
            import org.ow2.jasmine.jadort.client.flex.view.*;
            import com.adobe.cairngorm.control.CairngormEventDispatcher;
            import org.ow2.jasmine.jadort.client.flex.control.JadortControl;
            import mx.events.*;

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

            private var timer : Timer;

            private function reloadpage(event : MouseEvent) : void {
                // The location.reload's bReloadSource argument is set to false
                // so that the browser retrieves the data from cache if no
                // later version deployed on the Web server
                var ref : URLRequest = new URLRequest("javascript:location.reload(false)");
                navigateToURL(ref, "_self");
            }

            private function closepage(event : MouseEvent) : void {
                var ref : URLRequest = new URLRequest("javascript:window.close()");
                navigateToURL(ref, "_self");
            }

            // data initialization
            private function init() : void {
                // add listener to changer the step of the progress engine step in the top
                CairngormEventDispatcher.getInstance().addEventListener(
                    ProgressStateEvent.EVENT_PROGRESS_STATE, topEngineStep);
                var initializeEvent : InitializeEvent = new InitializeEvent();
                CairngormEventDispatcher.getInstance().dispatchEvent(initializeEvent);
                var getOperationsListEvent : GetOperationsListEvent = new GetOperationsListEvent();
                CairngormEventDispatcher.getInstance().dispatchEvent(getOperationsListEvent);
            }

            // each 4 mS the progress bar will progress in the progress state engine in the top menu
            private function timer_progress1(evt : TimerEvent) : void {
                progressBar1.setProgress(progressBar1.value + 4, 100);
            }
            private function timer_progress2(evt : TimerEvent) : void {
                progressBar2.setProgress(progressBar2.value + 4, 100);
            }
            public function timer_progress3(evt : TimerEvent) : void {
                progressBar3.setProgress(progressBar3.value + 4, 100);
            }
            private function timer_progress4(evt : TimerEvent) : void {
                progressBar4.setProgress(progressBar4.value + 4, 100);
            }

            // this function will be called when the progress bar are completed
            private function progressBar_complete(evt : Event, textBoxStep : TextArea) : void {
                textBoxStep.setStyle("styleName", "topProgressNumber2");
                if (timer != null) {
                    timer.stop();
                }
            }

            // do checks and if OK go to the next step
            private function nextStep() : void {
                if (timer != null) {
                    timer.stop();
                }

                if ((model.index == 8 || model.index == 9)
                 && (model.serverProgressList != null && model.serverProgressList.length > 0)
                 && (model.serverProgressList.getItemAt(0).vmImage == null)
                 && (model.serverProgressList.getItemAt(0).progress == 40 || model.serverProgressList.getItemAt(0).progress == 50)
                 ) {
                    // Maintenance is manual if no VM is used 
                    CustomAlert.info("The servers are stopped and therefore ready for maintenance.\n"
                        + "Please do all necessary maintenance manually and press OK when finished.\n\n"
                        + "To save the current operation and quit JaDOrT, close this window.", shouldGoNext);
                    return;
                }

                if (model.index == 7) {
                    // Don't go next, select the servers instead
                    CairngormEventDispatcher.getInstance().dispatchEvent(
                        new SelectServersEvent(model.selectedServers));
                    return;
                }

                if (model.serverProgressList != null && model.serverProgressList.length > 0) {
                    if ((model.index == 5 && model.serverProgressList.getItemAt(0).progress == 0)
                     || (model.index == 9 && model.serverProgressList.getItemAt(0).progress == 33)) {
                        if (model.totalActiveSessions != 0) {
                            // We're about to:
                            //    - undeploy an application
                            //    - or stop a server in a farm
                            // and there are active user sessions
                            //
                            // Don't go next, warn instead
                            if (model.index == 5) {
                                CustomAlert.confirm("There are " + model.totalActiveSessions
                                    + " users on the old version!\n\n"
                                    + "Are you sure you want to undeploy it?", shouldGoNext);
                            } else {
                                CustomAlert.confirm("There are " + model.totalActiveSessions
                                    + " users connected to the server(s)!\n\n"
                                    + "Are you sure you want to stop the server(s)?", shouldGoNext);
                            }
                            return;
                        }
                    } else if (model.index == 5 && model.serverProgressList.getItemAt(0).progress == 50) {
                        // We're about to delete the old version
                        //
                        // Don't go next, warn instead
                        CustomAlert.confirm("Once the old version is deleted, the action cannot be undone.\n\n"
                            + "Are you sure you want to continue?", shouldGoNext);
                        return;
                    } else if (model.index == 13 && model.serverProgressList.getItemAt(0).progress == 0) {
                        // We're about to destroy a VM host
                        //
                        // Don't go next, warn instead
                        CustomAlert.confirm("Once a VM host is destroyed, the action cannot be undone.\n\n"
                            + "Are you sure you want to continue?", shouldGoNext);
                        return;
                    }
                }

                goNext();
            }

            // go to the next step
            private function goNext() : void {
                CairngormEventDispatcher.getInstance().dispatchEvent(new NextEvent());
            }

            // go to the next step based on the result of a confirmation
            private function shouldGoNext(result : Object) : void {
                if (result.detail == Alert.YES || result.detail == Alert.OK) {
                    CairngormEventDispatcher.getInstance().dispatchEvent(new NextEvent());
                }
            }

            private function getStep(index : Number) : Number {
                if (index == 1) {
                    // Initialize topology
                    return 0;
                } else if (index == 2) {
                    // Select group
                    return 1;
                } else if (index == 11) {
                    // Operation type
                    return 2;
                } else if (index == 3) {
                    // Select application
                    return 2;
                } else if (index == 10) {
                    // Select VM image (global)
                    return 2;
                } else if (index == 7 || index == 12) {
                    // Select servers to maintain or VM image to deploy on server
                    return 2;
                } else if (index == 4 || index == 5 || index == 8 || index == 9 || index == 13) {
                    // Migration or maintenance progress
                    return 3;
                } else if (index == 6) {
                    // Finished
                    return 4;
                } else {
                    return -1;
                }
            }

            // change the engine state in the top + handle transition from step to step
            private function topEngineStep(evt : ProgressStateEvent) : void {
                // Transitions
                var oldStep : Number = this.getStep(evt.oldIndex);
                var newStep : Number = this.getStep(evt.newIndex);
                var timer : Timer = null;

                if (oldStep == -1) {
                    oldStep = newStep;
                }

                if (newStep > 3) {
                    if (oldStep < 3) {
                        timer = new Timer(10);
                        timer.addEventListener(TimerEvent.TIMER, timer_progress4);
                        timer.start();
                    } else {
                        progressBar4.setProgress(100, 100);
                    }
                    label5.text="End";
                } else {
                    progressBar4.setProgress(0, 0);
                    textBoxStep5.setStyle("styleName", "topProgressNumber");
                    label5.text="";
                }

                if (newStep > 2) {
                    if (oldStep < 2) {
                        timer = new Timer(10);
                        timer.addEventListener(TimerEvent.TIMER, timer_progress3);
                        timer.start();
                    } else {
                        progressBar3.setProgress(100, 100);
                    }
                    label4.text="Operation\nExecution";
                } else {
                    progressBar3.setProgress(0, 0);
                    textBoxStep4.setStyle("styleName", "topProgressNumber");
                    label4.text="";
                }

                if (newStep > 1) {
                    if (oldStep < 1) {
                        timer = new Timer(10);
                        timer.addEventListener(TimerEvent.TIMER, timer_progress2);
                        timer.start();
                    } else {
                        progressBar2.setProgress(100, 100);
                    }
                    label3.text="Operation\nArguments";
                } else {
                    progressBar2.setProgress(0, 0);
                    textBoxStep3.setStyle("styleName", "topProgressNumber");
                    label3.text="";
                }

                if (newStep > 0) {
                    if (oldStep < 0) {
                        timer = new Timer(10);
                        timer.addEventListener(TimerEvent.TIMER, timer_progress1);
                        timer.start();
                    } else {
                        progressBar1.setProgress(100, 100);
                    }
                    label2.text="Group\nSelection";
                } else {
                    progressBar1.setProgress(0, 0);
                    textBoxStep2.setStyle("styleName", "topProgressNumber");
                    label2.text="";
                }

                if (newStep > -1) {
                    textBoxStep1.setStyle("styleName", "topProgressNumber2");
                    label1.text="Topology\nInitialization";
                } else {
                    textBoxStep1.setStyle("styleName", "topProgressNumber");
                    label1.text="";
                }

                if (evt.newIndex == 7) {
                    if (!model.selectServerInfoDisplayed) {
                        var totalServers : Number = 0;
                        var maintainedServers : Number = 0;

                        if (model.servers != null) {
                            for each(var server : ServerVO in model.servers) {
                                totalServers++;
                                if (server.maintained) {
                                    maintainedServers++;
                                }
                            }
                        }

                        if (totalServers > 0 && maintainedServers > 0) {
                            Alert.show("You have maintained " + maintainedServers + " out of " + totalServers + " servers.\n\n"
                                + "Now, please select the other server(s) you would like to maintain in this roll "
                                + "and click \"Next\" in order to continue this maintenance operation.\n\n"
                                + "You can also close this window and resume the operation later.");

                            model.selectServerInfoDisplayed = true;
                        }
                    }
                } else {
                    model.selectServerInfoDisplayed = false;
                }

                // Top titles
                if (evt.newIndex == 1) {
                    mainPanel.title="Topology initialization for operation \"" + model.currentOperation.name + "\"";
                    // label1.text set by "Transitions"
                } else if (evt.newIndex == 2) {
                    mainPanel.title="Group selection for operation \"" + model.currentOperation.name + "\"";
                    // label2.text set by "Transitions"
                } else if (evt.newIndex == 3) {
                    mainPanel.title="Application selection for operation \"" + model.currentOperation.name + "\"";
                    label3.text="Application\nUpload";
                } else if (evt.newIndex == 4 || evt.newIndex == 5) {
                    mainPanel.title="Migration execution for operation \"" + model.currentOperation.name + "\"";
                    label4.text="Migration\nExecution";
                } else if (evt.newIndex == 6) {
                    mainPanel.title="Operation \"" + model.currentOperation.name + "\" completed - Congratulations !";
                    // label5.text set by "Transitions"
                } else if (evt.newIndex == 7) {
                    mainPanel.title="Servers selection for operation \"" + model.currentOperation.name + "\"";
                    label3.text="Servers\nSelection";
                } else if (evt.newIndex == 8 || evt.newIndex == 9) {
                    mainPanel.title="Maintenance execution for operation \"" + model.currentOperation.name + "\"";
                    label4.text="Maintenance\nExecution";
                } else if (evt.newIndex == 10) {
                    mainPanel.title="VM image selection for operation \"" + model.currentOperation.name + "\"";
                    label3.text="VM Image\nSelection";
                } else if (evt.newIndex == 11) {
                    mainPanel.title="Operation type Selection for operation \"" + model.currentOperation.name + "\"";
                    label3.text="Operation type\nSelection";
                } else if (evt.newIndex == 12) {
                    if (model.selectedServer == null) {
                        mainPanel.title="VM image selection for server - Loading servers list...";
                    } else {
                        mainPanel.title = "VM image selection for server \"" + model.selectedServer.name + "\"";
                    }
                    label3.text="VM Image\nSelection";
                } else if (evt.newIndex == 13) {
                    mainPanel.title="Destroy the old VM hosts for operation \"" + model.currentOperation.name + "\"";
                    label3.text="Destroy old\nVM hosts";
                }
            }

            // go to the previous step
            private function previousStep() : void {
                CustomAlert.confirm("Are you sure ?", previousConfirmHandler);
            }

            private function previousConfirmHandler(event:CloseEvent) : void {
                if (event.detail == Alert.YES) {
                    CairngormEventDispatcher.getInstance().dispatchEvent(new PreviousEvent());
                }
            }
        ]]>
    </mx:Script>

    <business:Services id="services" />

    <mx:ApplicationControlBar id ="ApplicationControlBar" styleName="gradientBackground" dock="true" paddingTop="0" paddingBottom="0" width="100%" x="-1" y="-1">
        <mx:Grid width="100%" >
            <mx:GridRow width="100%" >
                <mx:GridItem width="100%" >
                    <mx:Label width="100%" text="JaDOrT Web Console" fontSize="20" />
                </mx:GridItem>

                <mx:GridItem width="100%" verticalAlign="middle" horizontalAlign="right" >
                    <mx:Button label="Go to JaDOrT Home" click="reloadpage(event)" />
                    <mx:Button label="Save the current operation and quit JaDOrT" click="closepage(event)" enabled="{model.index > 0}" />
                </mx:GridItem>
            </mx:GridRow>
        </mx:Grid>
    </mx:ApplicationControlBar>

    <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" id="Engine" width="800" height="112" cornerRadius="20" borderColor="#CBC9C9" borderStyle="solid" borderThickness="1" backgroundColor="#FFFFFF" horizontalCenter="-1" top="10">
        <mx:TextArea x="204.15" width="35" height="35" text="1" styleName="topProgressNumber" id="textBoxStep1" verticalCenter="-26" editable="false" selectable="false" />
        <mx:ProgressBar width="55" height="11" label="" id ="progressBar1" mode="manual" styleName="topProgressBar" horizontalCenter="-134" verticalCenter="-24" complete="progressBar_complete(event, textBoxStep2);" />
        <mx:TextArea width="35" height="35" text="2" id="textBoxStep2" styleName="topProgressNumber" horizontalCenter="-90" verticalCenter="-26" editable="false" selectable="false" />
        <mx:ProgressBar width="55" height="11" label="" id ="progressBar2" mode="manual" styleName="topProgressBar" horizontalCenter="-46" verticalCenter="-24" complete="progressBar_complete(event, textBoxStep3);" />
        <mx:TextArea width="35" height="35" text="3" styleName="topProgressNumber" id="textBoxStep3" horizontalCenter="-2" verticalCenter="-26" editable="false" selectable="false" />
        <mx:ProgressBar width="55" height="11" label="" id ="progressBar3" mode="manual" styleName="topProgressBar" horizontalCenter="42" verticalCenter="-24" complete="progressBar_complete(event, textBoxStep4);" />
        <mx:TextArea width="35" height="35" text="4" styleName="topProgressNumber" id="textBoxStep4" horizontalCenter="86" verticalCenter="-26" editable="false" selectable="false" />
        <mx:ProgressBar width="55" height="11" label="" id ="progressBar4" mode="manual" styleName="topProgressBar" horizontalCenter="130" verticalCenter="-24" complete="progressBar_complete(event, textBoxStep5);" />
        <mx:TextArea width="35" height="35" text="5" styleName="topProgressNumber" id="textBoxStep5" horizontalCenter="174" verticalCenter="-26" editable="false" selectable="false" />
        <mx:Label id="label1" x="178" height="49" width="96" styleName="textWorkflow" verticalCenter="20" />
        <mx:Label id="label2" height="49" width="96" styleName="textWorkflow" horizontalCenter="-90" verticalCenter="20" />
        <mx:Label id="label3" height="49" width="96" styleName="textWorkflow" horizontalCenter="-3" verticalCenter="20" />
        <mx:Label id="label4" height="49" width="96" styleName="textWorkflow" horizontalCenter="86" verticalCenter="20" />
        <mx:Label id="label5" height="49" width="96" styleName="textWorkflow" horizontalCenter="174" verticalCenter="20" />
    </mx:Canvas>

    <mx:Panel verticalScrollPolicy="off" horizontalScrollPolicy="off" title="Operation Selection" id="mainPanel"
        height="100%" width="800" paddingTop="10" paddingLeft="10" paddingRight="10" paddingBottom="10" cornerRadius="20" verticalCenter="150" horizontalCenter="-1">

        <!-- verticalScrollPolicy and horizontalScrollPolicy have no effect in mx:ViewStack -->
        <mx:ViewStack borderStyle="solid" width="760" height="100%" paddingBottom="15" paddingTop="15" paddingLeft="0" paddingRight="0" selectedIndex="{model.index}" >
            <view:SelectOperation horizontalScrollPolicy="off" />
            <view:UploadTopologyFile horizontalScrollPolicy="off" />
            <view:SelectGroup horizontalScrollPolicy="off" />
            <view:SelectApplication horizontalScrollPolicy="off" />
            <view:ExecuteMigration horizontalScrollPolicy="off" />
            <view:UndeployEraseApplication horizontalScrollPolicy="off" />
            <view:Finished horizontalScrollPolicy="off" />
            <view:SelectServers horizontalScrollPolicy="off" />
            <view:ExecuteMaintenanceCluster horizontalScrollPolicy="off" />
            <view:ExecuteMaintenanceNoCluster horizontalScrollPolicy="off" />
            <view:SelectVMImage horizontalScrollPolicy="off" />
            <view:SelectOperationType horizontalScrollPolicy="off" />
            <view:SelectVMImageForServer horizontalScrollPolicy="off" />
            <view:DestroyOldVMs horizontalScrollPolicy="off" />
        </mx:ViewStack>

        <mx:HBox width="760" horizontalAlign="center" horizontalGap="20">
            <mx:Label text="" width="200" visible="false" />
            <mx:Button label="Undo" click="previousStep()" enabled="{model.previousButtonEnabled}" width="76" />
            <mx:Button label="Next" click="nextStep()" width="76" enabled="{model.nextButtonEnabled}" />
            <mx:Image source="@Embed(source='ClickNext.gif')" width="29" visible="{model.nextButtonEnabled}" />
            <mx:Label text="Click next to continue" width="130" visible="{model.nextButtonEnabled}" />
         </mx:HBox>
    </mx:Panel>

    <control:JadortControl id="controller" />
</mx:Application>
