/*
 * JBoss, the OpenSource WebOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.web.loadbalancer.scheduler;

/**
 * This class holds statistics for a node.
 *
 * @author Thomas Peuss <jboss@peuss.de>
 * @version $Revision: 1.3 $
 */
public class HostStatistics
{
  private static final int NUM_SAMPLES=50;

  private volatile long numRequests;
  private volatile long sumResponseTime;
  private volatile int currentConnections=0;
  private volatile int[] lastResponseTimes=new int[NUM_SAMPLES];
  private volatile int index=0;

  public void addRequest(int responseTime)
  {
    numRequests++;
    sumResponseTime+=responseTime;

    try
    {
        lastResponseTimes[index]=responseTime;
        index++;
    }
    catch (ArrayIndexOutOfBoundsException aioobe)
    {
        index=0;
    }
  }

  public void reset()
  {
    sumResponseTime=0L;
    numRequests=0L;
    lastResponseTimes=new int[NUM_SAMPLES];
    index=0;
  }

  public int getAvgResponseTime()
  {
    return sumLastResponseTimes()/NUM_SAMPLES;
  }

  public long getNumRequests()
  {
    return numRequests;
  }

  public long getSumResponseTime()
  {
    return sumResponseTime;
  }

  public int getCurrentConnections()
  {
    return currentConnections;
  }

  public void incCurrentConnections()
  {
     currentConnections++;
  }

  public void decCurrentConnections()
  {
     currentConnections--;
  }

  public String toString()
  {
    return "[CurrentConnections="+currentConnections+", Requests="+numRequests+", AvgResponseTime="+getAvgResponseTime()+"]";
  }

  private int sumLastResponseTimes()
  {
     int sum=0;

     for (int i=0;i<NUM_SAMPLES;++i)
     {
        sum+=lastResponseTimes[i];
     }
   
     return sum;
  }
}
