/**
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * Licensed 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 io.fabric8.kubernetes.client.internal.readiness;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.KubernetesClientTimeoutException;
import io.fabric8.kubernetes.client.Watcher;

public class ReadinessWatcher<T extends HasMetadata> implements Watcher<T> {

  private final BlockingQueue<T> queue = new ArrayBlockingQueue<>(1);

  private final T resource;

  public ReadinessWatcher(T resource) {
    this.resource = resource;
  }

  public void eventReceived(Action action, T resource) {
    switch (action) {
      case MODIFIED:
        if (Readiness.isReady(resource)) {
          queue.add(resource);
        }
        break;
      default:
    }
  }

  @Override
  public void onClose(KubernetesClientException e) {

  }

  public T await(long amount, TimeUnit timeUnit) {
    try {
      T item = queue.poll(amount, timeUnit);
      if (item != null) {
        return item;
      }
      throw new KubernetesClientTimeoutException(resource, amount, timeUnit);
    } catch (InterruptedException e) {
      throw new KubernetesClientTimeoutException(resource, amount, timeUnit);
    }
  }
}

@@ -685,34 +685,30 @@
 current.
-ArrayBlockingQueue
+CountDownLatch
 ;%0Aimport
@@ -729,29 +729,24 @@
 current.
-BlockingQueue
+TimeUnit
 ;%0Aimport
@@ -767,24 +767,38 @@
 current.
-TimeUnit
+atomic.AtomicReference
 ;%0A%0Aimpor
@@ -1101,16 +1101,17 @@
 r%3CT%3E %7B%0A%0A
+%0A
   privat
@@ -1122,59 +1122,123 @@
 nal 
-BlockingQueue%3CT%3E queue = new ArrayBlockingQueu
+CountDownLatch latch = new CountDownLatch(1);%0A  private final AtomicReference%3CT%3E reference = new AtomicReferenc
 e%3C%3E(
-1
 );%0A%0A
@@ -1498,26 +1498,59 @@
     
-queue.add(resource
+reference.set(resource);%0A          latch.countDown(
 );%0A 
@@ -1741,69 +1741,41 @@
     
-T item = queue.poll(amount, timeUnit);%0A      if (item != null
+if (latch.await(amount, timeUnit)
 ) %7B%0A
@@ -1793,12 +1793,23 @@
 urn 
-item
+reference.get()
 ;%0A  

fix (waituntilready): Can now handle multiple events.