/*
** Module   : SequentialElements.java
** Abstract : represents elements to be processed in order on a single thread
**
** Copyright (c) 2009, Golden Code Development Corporation.
**
** -#- -I- --Date-- -----------------------Description------------------------
** 001 GES 20090319 Represents elements to be processed in order on a single
**                  thread.
*/

/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program 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 Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.goldencode.harness;

import java.util.concurrent.*;
import com.goldencode.harness.test.*;

/**
 * Represents elements to be processed in order on a single thread. If any
 * element is processed with a failed status, all the rest of the elements
 * will be marked failed and will no longer be returned.
 * 
 * @param   <E>
 *          Type of element.
 */
public class SequentialElements<E extends Test>
implements SubQueue<E>,
           Dependent
{
   /** The contained elements. */
   private final LinkedBlockingQueue<E> queue;
   
   /** Synchronization primitive (more granular than "this"). */
   private final Object lock = new Object();
   
   /** The specific thread on which the tests must run. */
   private Thread bound = null;
   
   /**
    * Construct an instance representing multiple elements which must execute
    * simultaneously.
    */
   public SequentialElements()
   {
      queue = new LinkedBlockingQueue<E>();
   }
   
   /**
    * Add an element to the end of the queue.
    *
    * @param    element
    *           The element to add.
    */
   public void add(E element)
   {
      synchronized (lock)
      {
         try
         {
            element.addDependent(this);
            queue.put(element);
         }
         
         catch (InterruptedException ie)
         {
            throw new RuntimeException("Cannot put element in queue.");
         }
      }
   }
   
   /**
    * Reports if there are any elements remaining in the queue. This can answer
    * the question of whether there will ever be elements available to
    * {@link #dequeue}. Note that due to dependencies between elements, it is
    * possible for a queue to be non-empty but to not yet be ready to accept
    * a <code>dequeue</code> request.
    *
    * @return   <code>true</code> if all queue elements have been dequeued.
    */
   public boolean isEmpty()
   {
      boolean empty = false;
      
      synchronized (lock)
      {
         empty = (queue.size() == 0);
      }
      
      return empty;
   }
   
   /**
    * Reports if the queue has elements to {@link #dequeue}. This will be
    * <code>false</code> if there are no elements remaining OR if the elements
    * that are contained have dependencies upon other elements such that no
    * dequeuing is possible until the dependencies are satisfied. In such a
    * case the queue is considered not ready.
    *
    * @return   <code>true</code> if the queue contains at least one element
    *           which is ready to be dequeued AND the calling thread is the
    *           thread on which the tests must run.
    */
   public boolean isReady()
   {
      return !isEmpty() && (bound == null || bound == Thread.currentThread());
   }
   
   /**
    * Reports if the queue acts as a barrier. A barrier is a sub-queue that
    * ends the search for elements until such time as the barrier sub-queue is
    * the first sub-queue. This is a mechanism to force all prior sub-queues to
    * be fully processed before any following sub-queues can be processed.
    * <p>
    * Barriers DO NOT have any elements of their own to return. Rather, they
    * just are a marker of known "sections" of the containing queue.
    *
    * @return   Always <code>false</code>.
    */
   public boolean isBarrier()
   {
      return false;
   }
   
   /**
    * Associates the next element in the queue with the caller, without
    * actually calling {@link #dequeue} which can block. This allows the
    * calling code to release any resources before the subsequent potentially
    * blocking operation. Any subsequent call to {@link #isReady} MUST take
    * this reservation into account. This means that all calls to this method
    * must be matched with a subsequent call to <code>dequeue</code>.
    *
    * @return   <code>true</code> if the reservation was successful. Otherwise
    *           the queue is not ready and caller MUST NOT call
    *           <code>dequeue</code>. 
    */
   public boolean reserve()
   {
      synchronized (lock)
      {
         Thread current = Thread.currentThread();
         
         if (bound == null)
         {
            bound = current;
         }
         else
         {
            if (bound != current)
            {
               String spec = "Invalid reservation (called from %s but " +
                             "expected to be called from %s).";
               throw new RuntimeException(String.format(spec,
                                                        current.getName(),
                                                        bound.getName()));
            }
         }
         
         return true;
      }
   }
   
   /**
    * Obtain the next element from the queue.
    *
    * @return   The element or <code>null</code> if the element was previously
    *           retrieved.
    */
   public E dequeue()
   {
      E element = null;
      
      synchronized (lock)
      {
         // remove the object we are going to return later
         element = queue.poll();
      }
      
      return element;
   }
   
   /**
    * Reports on the disposition of an activity on which this object is
    * dependent.
    *
    * @param    status
    *           The status of the activity.
    * @param    reason
    *           Details on the cause of any failure.
    */
   public void update(Status status, String reason)
   {
      synchronized (lock)
      {
         if (status != Status.PASSED)
         {
            while (queue.size() > 0)
            {
               Test element = queue.poll();
               element.setStatus(Status.FAILED_DEPENDENCY, reason);
            }
         }
      }
   }
}
