import Message;

public class MsgQueue
{
   private Message [] list;
   private int count;
   private int front;
   private int rear;
   private final int GROW_AMOUNT = 5;

   /**
   Default constructor
   */
   public MsgQueue()
   {
      list = new Message[ GROW_AMOUNT ];
      front = 0;
      rear = 0;
      count = 0;
   }

   /**
   Adds an Object to the rear of the queue
   does nothing if queue is full
   @param x is the Object to add to the queue
   */
   public void add( Message x )
   {
      if( isFull() )
         grow( GROW_AMOUNT );
      list[ rear ] = x;
      rear = ( rear + 1 ) % list.length;
      count++;
   }

   /**
   Remove the element from the front of the queue
   @returns the Object at the front of the queue
      if queue is empty returns null
   */
   public Message remove()
   {
      Message temp = null;
      if( count > 0 )
      {
         temp = list[ front ];
         front = ( front + 1 ) % list.length;
         count--;
      }
      if( count < ( list.length - GROW_AMOUNT -1 ) )
         grow( -GROW_AMOUNT );
      return temp;
   }

   /**
   Grow or shrink the queue per specified amount
   @param amount is the amount to grow/shrink by
   */
   private void grow( int amount )
   {
      Message [] temp = new Message[ list.length + amount ];
      int index = 0;
      while( index < count )
      {
         temp[index] = list[ front ];
         front = ( front + 1 ) % list.length;
         index++;
      }
      front = 0;
      rear = index;
      list = temp;
   }
   /**
   Is the queue empty
   @returns true if the queue is empty else returns false
   */
   public boolean isEmpty()
   {
      return count == 0;
   }

   /**
   Is the queue full
   @returns true if the queue is full else returns false
   */
   public boolean isFull()
   {
      return count == list.length;
   }

   /**
   Clears the queue (Throws out all in the queue)
   */
   public void clear()
   {
      front = 0;
      rear = 0;
      count = 0;
      grow( -( list.length - GROW_AMOUNT ) );
   }
}

