package csc454.net;
import java.awt.*;
import java.util.*;

public class queue {
  protected double w_[]; //this array will hold queue entry time for messages
  protected TextArea txt_;  // where to print messages
  protected int num_;  //station number
  protected int count_=0;
  protected int totCnt_=0;
  protected int totTime_=0;
  protected time t_;
  protected boolean terminate_=false;

  public queue(TextArea txt, int num) {
    txt_=txt;
    num_=num;
    w_= new double[1000];
  }

  public void begin (time t) {
    t_=t;
  }

  public synchronized void terminate() {
    terminate_=true;
    double avgTime= totTime_/(double)totCnt_;
    txt_.appendText("Queue " + num_ +" had a total of " + totCnt_ + 
                    " Messages with an average waiting time of " +
                    avgTime + ". This queue is currently holding " +
                    count_ + " Messages at " + (t_.elapsed()/1000.0)+
                    "time of Termination\n");
    notifyAll();
  }

  public synchronized void enqueue() {
    count_++; 
    w_[count_-1]=t_.elapsed();//remember entry time for message
    notifyAll(); 
  }
  public synchronized boolean dequeue() {
    while (count_ <= 0 & !terminate_) 
      try { wait(); } catch(InterruptedException ex) {}
    if(terminate_) {
      return false;
    }
    else {
      double w=t_.elapsed()-w_[0];
      totTime_ +=w;
      count_--;
      for (int i=count_-1;i>0;i--){w_[i-1]=w_[i];}
      totCnt_++;
    }
    return true;
  }

public   boolean empty(){return count_ == 0;}
public   boolean full(){return false;}
}


