package nl.jpoint.vertx.mod.cluster.handler.internal;

import nl.jpoint.vertx.mod.cluster.aws.AwsAutoScalingUtil;
import nl.jpoint.vertx.mod.cluster.aws.AwsElbUtil;
import nl.jpoint.vertx.mod.cluster.aws.AwsException;
import nl.jpoint.vertx.mod.cluster.aws.AwsState;
import nl.jpoint.vertx.mod.cluster.request.DeployRequest;
import nl.jpoint.vertx.mod.cluster.util.LogConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.json.JsonObject;

import java.util.List;


public class AwsAsRegistrationStatusPollingHandler implements Handler<Long> {

    private static final Logger LOG = LoggerFactory.getLogger(AwsAsRegistrationStatusPollingHandler.class);
    private final DeployRequest request;
    private final AwsAutoScalingUtil asUtil;
    private final AwsElbUtil elbUtil;
    private final Vertx vertx;
    private final AwsState state;

    private List<String> loadbalancers = null;

    public AwsAsRegistrationStatusPollingHandler(final DeployRequest request, final AwsAutoScalingUtil asUtil, final AwsElbUtil elbUtil, final Vertx vertx, final AwsState state) {
        this.request = request;
        this.asUtil = asUtil;
        this.elbUtil = elbUtil;
        this.vertx = vertx;

        this.state = state;

        LOG.info("[{} - {}]: Waiting for instance {} status in auto scaling group {} to reach {}.", LogConstants.AWS_AS_REQUEST, request.getId(), request.getInstanceId(), request.getAutoScalingGroup(), state);
    }

    public AwsAsRegistrationStatusPollingHandler(DeployRequest request, AwsAutoScalingUtil awsAsUtil, Vertx vertx, AwsState standby) {
        this(request, awsAsUtil, null, vertx, standby);
    }

    @Override
    public void handle(Long timer) {
        try {
            AwsState currentState = asUtil.getInstanceState(request.getInstanceId(), request.getAutoScalingGroup());
            LOG.info("[{} - {}]: Instance {} in auto scaling group {} in state {}", LogConstants.AWS_AS_REQUEST, request.getId(), request.getInstanceId(), request.getAutoScalingGroup(), currentState.name());
            if (state.equals(currentState) && checkElbInService()) {
                vertx.cancelTimer(timer);
                vertx.eventBus().send("aws.service.deploy", new JsonObject().putBoolean("success", true)
                        .putString("id", request.getId().toString())
                        .putString("state", state.toString()));
            }
        } catch (AwsException e) {
            LOG.error("[{} - {}]: Error executing de-register", LogConstants.AWS_AS_REQUEST, request.getId(), e.getMessage());
        }

    }

    private boolean checkElbInService() {
        if (AwsState.INSERVICE.equals(state) && elbUtil != null) {
            if (loadbalancers == null) {
                try {
                    loadbalancers = asUtil.listLoadBalancers(request.getAutoScalingGroup());

                } catch (AwsException e) {
                    LOG.error("[{} - {}]: Error executing list elb in auto scaling group request", LogConstants.AWS_AS_REQUEST, request.getId(), e.getMessage());
                }
            }

            for (String loadbalancer : loadbalancers) {
                try {
                    LOG.info("[{} - {}]: Cheking Instance {} state on elb {}", LogConstants.AWS_AS_REQUEST, request.getId(), request.getInstanceId(), loadbalancer);
                    AwsState currentElbState = elbUtil.getInstanceState(request.getInstanceId(), loadbalancer);
                    LOG.info("[{} - {}]: Instance {} on elb {} in state {}", LogConstants.AWS_AS_REQUEST, request.getId(), request.getInstanceId(), loadbalancer, currentElbState.name());
                    if (!AwsState.INSERVICE.equals(currentElbState)) {
                        return false;
                    }
                } catch (AwsException e) {
                    LOG.error("[{} - {}]: Error executing list elb state for instance {} on elb {} with error", LogConstants.AWS_AS_REQUEST, request.getId(), request.getInstanceId(), loadbalancer, e.getMessage());
                    return false;
                }
            }
            LOG.info("[{} - {}]: Instance {}  in service on all elb's {}.", LogConstants.AWS_AS_REQUEST, request.getId(), request.getInstanceId());
            return true;
        }
        return true;
    }
}

@@ -940,24 +940,56 @@
 State state;
+%0A    private final long timeout;
 %0A%0A    privat
@@ -1328,17 +1328,16 @@
  vertx;%0A
-%0A
         
@@ -1357,16 +1357,79 @@
 state;%0A%0A
+        this.timeout = System.currentTimeMillis() + + 240000;%0A%0A
         
@@ -2570,24 +2570,368 @@
 String()));%0A
+            %7D else if (System.currentTimeMillis() %3E timeout) %7B%0A                vertx.cancelTimer(timer);%0A                vertx.eventBus().send(%22aws.service.deploy%22, new JsonObject().putBoolean(%22success%22, false)%0A                        .putString(%22id%22, request.getId().toString())%0A                        .putString(%22state%22, state.toString()));%0A
             

Set timeout on poller