/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.geronimo.st.v30.core.commands;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

import javax.enterprise.deploy.shared.CommandType;
import javax.enterprise.deploy.spi.status.DeploymentStatus;
import javax.enterprise.deploy.spi.status.ProgressEvent;
import javax.enterprise.deploy.spi.status.ProgressListener;
import javax.enterprise.deploy.spi.status.ProgressObject;

import org.apache.geronimo.st.v30.core.Activator;
import org.apache.geronimo.st.v30.core.DeploymentStatusMessage;
import org.apache.geronimo.st.v30.core.internal.Trace;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.wst.server.core.IModule;

/**
 * This class is a wrapper IDeploymentCommand that when executed blocks the
 * callee's thread until completed, either when the waiting thread times out, or
 * a failed or completed notification is recieved from the DeploymentManager.
 *
 * @version $Rev$ $Date$
 */
public class SynchronizedDeploymentOp implements ProgressListener,
        IDeploymentCommand {

    private IDeploymentCommand command;

    private MultiStatus status = null;

    private IProgressMonitor _monitor = null;

    private boolean timedOut = true;

    public SynchronizedDeploymentOp(IDeploymentCommand command) {
        super();
        this.command = command;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.geronimo.core.commands.IDeploymentCommand#execute(org.eclipse.core.runtime.IProgressMonitor)
     */
    public IStatus execute(IProgressMonitor monitor) throws Exception {

        _monitor = monitor;

        if (_monitor == null) {
            _monitor = new NullProgressMonitor();
        }

        ProgressObject po = run();

        return new DeploymentCmdStatus(status, po);
    }

    private synchronized ProgressObject run() throws Exception {
        Trace.trace(Trace.INFO, "--> run()", Activator.traceCommands);
        
        IStatus ds = command.execute(_monitor);

        ProgressObject po = null;

        if (ds instanceof DeploymentCmdStatus) {
            po = ((DeploymentCmdStatus) ds).getProgressObject();
            po.addProgressListener(this);

            try {
                wait(getTimeout());
            } catch (InterruptedException e) {
            }

            po.removeProgressListener(this);
            if (timedOut) {
                Trace.trace(Trace.ERROR, "Command Timed Out!", Activator.logCommands);
                status = new MultiStatus(Activator.PLUGIN_ID, 0, "", null);
                status.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, command.getCommandType() + " timed out.", null));
            }
        }

        Trace.trace(Trace.INFO, "<-- run()", Activator.traceCommands);
        return po;
    }

    private synchronized void sendNotification() {
        timedOut = false;
        Trace.trace(Trace.INFO, "notifyAll()", Activator.traceCommands);
        notifyAll();
    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.enterprise.deploy.spi.status.ProgressListener#handleProgressEvent(javax.enterprise.deploy.spi.status.ProgressEvent)
     */
    public void handleProgressEvent(ProgressEvent event) {
        DeploymentStatus deploymentStatus = event.getDeploymentStatus();
        if (deploymentStatus != null) {
            DeploymentStatusMessage dsm = new DeploymentStatusMessage(deploymentStatus);
            Trace.trace(Trace.INFO, dsm.toString(), Activator.traceCommands);
            _monitor.subTask(dsm.toString());
            if (command.getCommandType() == deploymentStatus.getCommand()) {
                if (deploymentStatus.isCompleted()) {
                    messageToStatus(IStatus.OK, dsm.getMessage(), false);
                    sendNotification();
                } else if (deploymentStatus.isFailed()) {
                    messageToStatus(IStatus.ERROR, dsm.getMessage(), true);
                    sendNotification();
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.geronimo.core.commands.IDeploymentCommand#getCommandType()
     */
    public CommandType getCommandType() {
        return command.getCommandType();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.geronimo.core.commands.IDeploymentCommand#getModule()
     */
    public IModule getModule() {
        return command.getModule();
    }
    
    public long getTimeout() {
        return command.getTimeout();
    }
    
    public void messageToStatus(int severity, String source, boolean error) {
        status = new MultiStatus(Activator.PLUGIN_ID, 0, "", null);
        try {
            BufferedReader in = new BufferedReader(new StringReader(source));
            String line;
            while ((line = in.readLine()) != null) {
                status.add(new Status(severity, Activator.PLUGIN_ID, 0,line, null));
            }
        } catch (IOException e) {

        }
    }
}

@@ -933,16 +933,98 @@
 gReader;
+%0Aimport java.util.concurrent.CountDownLatch;%0Aimport java.util.concurrent.TimeUnit;
 %0A%0Aimport
@@ -2127,16 +2127,22 @@
 private 
+final 
 IDeploym
@@ -2161,16 +2161,20 @@
 ommand;%0A
+    
 %0A    pri
@@ -2244,32 +2244,36 @@
 monitor = null;%0A
+    
 %0A    private boo
@@ -2273,31 +2273,35 @@
 ate 
-boolean timedOut = true
+CountDownLatch latch = null
 ;%0A%0A 
@@ -2369,25 +2369,8 @@
 ) %7B%0A
-        super();%0A
     
@@ -2392,24 +2392,30 @@
 d = command;
+      
 %0A    %7D%0A%0A    
@@ -2757,32 +2757,80 @@
 r();%0A        %7D%0A%0A
+        latch = new CountDownLatch(1);%0A        %0A
         Progress
@@ -2920,29 +2920,16 @@
 private 
-synchronized 
 Progress
@@ -3297,47 +3297,127 @@
     
-try %7B%0A                wait(getTimeout()
+boolean timedOut = false;%0A            try %7B%0A                timedOut = !latch.await(getTimeout(), TimeUnit.MILLISECONDS
 );%0A 
@@ -3978,21 +3978,8 @@
 ate 
-synchronized 
 void
@@ -4004,34 +4004,8 @@
 ) %7B%0A
-        timedOut = false;%0A
     
@@ -4033,25 +4033,32 @@
 .INFO, %22
-notifyAll
+sendNotification
 ()%22, Act
@@ -4092,17 +4092,23 @@
     
-notifyAll
+latch.countDown
 ();%0A
@@ -5642,29 +5642,30 @@
 %7D%0A    %0A    p
-ublic
+rivate
  void messag

fix synchronization problem (notify called before wait). use a latch instead