/**
 * 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: GetPageIndexCommand.as 3607 2009-05-04 13:44:15Z alitokmen $
 * --------------------------------------------------------------------------
 */
package org.ow2.jasmine.jadort.client.flex.command {

    import com.adobe.cairngorm.commands.ICommand;
    import com.adobe.cairngorm.control.*;
    import flash.utils.clearTimeout;
    import flash.utils.setTimeout;
    import mx.collections.ArrayCollection;
    import mx.managers.CursorManager;
    import mx.rpc.IResponder;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import org.ow2.jasmine.jadort.client.flex.business.*;
    import org.ow2.jasmine.jadort.client.flex.event.*;
    import org.ow2.jasmine.jadort.client.flex.model.JadortModelLocator;
    import org.ow2.jasmine.jadort.client.flex.vo.*;

    /**
     * Gets the current page index.
     */
    public class GetPageIndexCommand extends SequenceCommandWithErrorHandling implements IResponder {

        private static var my_timedProcess : uint = 0;

        override public function execute(event : CairngormEvent) : void {
            // delegate to the GetPageIndexDelegate to call the getPageIndex service
            var delegate : GetPageIndexDelegate = JadortModelLocator.getInstance().getPageIndexDelegate;
            delegate.responder = this;
            delegate.getPageIndex();
        }

        public function result(event : Object) : void {
            CursorManager.removeAllCursors();

            var server : ServerVO;
            var serverProgress : ServerProgressVO;
            var resultEvent : ResultEvent = event as ResultEvent;
            var pageIndex : Number = resultEvent.result as Number;
            var model : JadortModelLocator = JadortModelLocator.getInstance();

            // set attributes in the model
            var oldIndex : Number = model.index;
            model.index = pageIndex;

            if (model.index == 7 && model.selectedServers != null) {
                model.nextButtonEnabled = (model.selectedServers.length > 0);
            } else {
                model.nextButtonEnabled = model.currentOperation.canGoToNextStep;
            }
            model.previousButtonEnabled = model.currentOperation.canGoToPreviousStep;

            model.selectedGroup = model.currentOperation.selectedGroup;
            model.uploadedApplication = model.currentOperation.application;

            if (model.selectedGroup != null) {
                model.servers = model.selectedGroup.servers;
            } else {
                model.servers = null;
            }

            if (model.currentOperation.topology != null) {
                model.groups = model.currentOperation.topology.groups;
            } else {
                model.groups = null;
            }

            if (model.index == 7) {
                if (model.selectedServers != null && model.servers != null) {
                    // Set the maintained and selected servers
                    // Create a dummy list to ensure ArrayCollection.contains works
                    var selectedServers : ArrayCollection = new ArrayCollection();
                    for each(var oldServer : ServerVO in model.selectedServers) {
                        for each(server in model.servers) {
                            if (oldServer.id == server.id) {
                                selectedServers.addItem(server);
                                break;
                            }
                        }
                    }
                    model.selectedServers = selectedServers;
                } else {
                    model.selectedServers = new ArrayCollection();
                }
            } else {
                model.selectedServers = null;
            }

            if (model.currentOperation.serverProgressList != null) {
                model.serverProgressList = model.currentOperation.serverProgressList;
            } else {
                model.serverProgressList = null;
            }

            if (model.currentOperation.workerProgressList != null) {
                model.workerProgressList = model.currentOperation.workerProgressList;
            } else {
                model.workerProgressList = null;
            }

            model.totalActiveSessions = 0;
            if (model.index == 7) {
                if (model.servers != null) {
                    for each(server in model.servers) {
                        model.totalActiveSessions += server.activeSessions;
                    }
                }
            } else {
                if (model.serverProgressList != null) {
                    for each(serverProgress in model.serverProgressList) {
                        model.totalActiveSessions += serverProgress.server.activeSessions;
                    }
                }
            }

            if (model.index == 3 && model.uploadedApplication != null) {
                CairngormEventDispatcher.getInstance().dispatchEvent(new ApplicationSelectedEvent());
            }

            // Select VM image for a server, therefore select the server as well
            model.selectedServer = null;
            if (model.index == 12 && model.serverProgressList != null) {
                for each(serverProgress in model.serverProgressList) {
                    if (serverProgress.vmImage == null) {
                        model.selectedServer = serverProgress.server;
                        break;
                    }
                }

                if (model.selectedServer == null) {
                    // finished selecting images for all servers
                    super.nextEvent = new NextEvent();
                    executeNextCommand();
                    return;
                }
            }

            // Update the top UI
            CairngormEventDispatcher.getInstance().dispatchEvent(
                new ProgressStateEvent(oldIndex, pageIndex));

            // Update and refresh the progress UI
            if (model.index == 4 || model.index == 5 || model.index == 7 ||
                model.index == 8 || model.index == 9 || model.index == 12 || model.index == 13) {
                var serverWorkerProgressEvent : ServerWorkerProgressEvent = new ServerWorkerProgressEvent();
                CairngormEventDispatcher.getInstance().dispatchEvent(serverWorkerProgressEvent);

                if (my_timedProcess == 0) {
                    my_timedProcess = setTimeout(refreshIfNeeded, 3000);
                }
            } else {
                if (my_timedProcess != 0) {
                    clearTimeout(my_timedProcess);
                    my_timedProcess = 0;
                }
            }
        }

        public function refreshIfNeeded() : void {
            clearTimeout(my_timedProcess);
            my_timedProcess = 0;

            var model : JadortModelLocator = JadortModelLocator.getInstance();

            if (model.index == 4 || model.index == 5 || model.index == 7
             || model.index == 8 || model.index == 9 || model.index == 12 || model.index == 13) {
                var getCurrentOperationEvent : GetCurrentOperationEvent = new GetCurrentOperationEvent();
                getCurrentOperationEvent.showBusyCursor = false;
                CairngormEventDispatcher.getInstance().dispatchEvent(getCurrentOperationEvent);
            }
        }
    }
}
