package edu.uw.zookeeper.common;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;

import com.google.common.util.concurrent.AbstractIdleService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Service;

public abstract class ForwardingService extends AbstractIdleService {

    @Override
    protected Executor executor() {
        return MoreExecutors.sameThreadExecutor();
    }
    
    @Override
    protected void startUp() throws Exception {
        Service delegate = delegate();
        delegate.addListener(
                new Listener() {
                    @Override
                    public void stopping(State from) {
                        stopAsync();
                    }

                    @Override
                    public void terminated(State from) {
                        stopAsync();
                    }

                    @Override
                    public void failed(State from, Throwable failure) {
                        stopAsync();
                    }}, 
                MoreExecutors.sameThreadExecutor());
        
        if (delegate.state() == State.FAILED) {
            throw new ExecutionException(delegate.failureCause());
        } else if (delegate.state() == State.TERMINATED) {
            throw new IllegalStateException();
        }
        
        delegate.startAsync();
        delegate.awaitRunning();
    }

    @Override
    protected void shutDown() throws Exception {
        delegate().stopAsync();
        delegate().awaitTerminated();
    }

    protected abstract Service delegate();
}

@@ -1151,19 +1151,14 @@
     
-%0A        if
+switch
  (de
@@ -1175,140 +1175,202 @@
 te()
- == State.FAILED) %7B%0A            throw new ExecutionException(delegate.failureCause());%0A        %7D else if (delegate.state() == State.
+) %7B%0A        case NEW:%0A            delegate.startAsync();%0A        case STARTING:%0A            delegate.awaitRunning();%0A        case RUNNING:%0A            break;%0A        case STOPPING:%0A        case 
 TERM
@@ -1375,19 +1375,17 @@
 RMINATED
-) %7B
+:
 %0A       
@@ -1428,25 +1428,36 @@
 ();%0A        
-%7D
+case FAILED:
 %0A        %0A  
@@ -1457,72 +1457,76 @@
     
-%0A
     
-    delegate.startAsync();%0A        delegate.awaitRunning();
+throw new ExecutionException(delegate.failureCause());%0A        %7D
 %0A   

fix for new Guava Service API