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

public class arrival implements Runnable {
  protected queue q_;    // reference to server queue
  protected TextArea txt_;  // where to print messages
  protected double min_; //min delay
  protected double max_; //max delay
  protected double norm_;//normalization multipler
  protected int num_;  //station number
  protected time t_;
  protected int cnt_=0;
  protected boolean terminate_=false;
  protected boolean begin_=false;

  public arrival(queue q, TextArea txt, int num, double min, double max,
                 double norm) {
    min_=min;
    max_=max;
    norm_=norm;
    q_=q; 
    txt_ = txt;
    num_=num;
  }

  public synchronized void begin (time t) {
     t_=t;
     begin_=true;
     notifyAll(); // signal thread waiting in run
   }
 
   public void terminate() {
     terminate_=true;
   }
 
   public synchronized void run() { 
     while (!begin_) {   // wait until begin called
       try { wait(); }         // woken up from turn method
       catch (InterruptedException ex) { return; }
     }
     try {
       long delay = (long)((min_+Math.random() * max_) * norm_);
       Thread.currentThread().sleep(delay);
       for(;!terminate_;) {
         cnt_=cnt_+1;
         txt_.appendText("Arrival occurred for station" + num_ + " at time " +
                         (t_.elapsed()/1000.0)+"\n");
         q_.enqueue();//put on queue
         delay = (long)((min_+Math.random() * max_) * norm_);
         Thread.currentThread().sleep(delay);
       }
       txt_.appendText(cnt_ + "Arrivals, at an inter-arrival rate of " + 
                       (t_.elapsed()/(double)cnt_/1000.0) + 
                       " seconds occurred for station " + num_ +" in "+
                       (t_.elapsed()/1000.0)+ " seconds of simulation\n");
     }
     catch (InterruptedException e) { return; }
   }
}

