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

import java.net.URL;
import java.util.Comparator;
import java.util.Collections;
import java.util.NoSuchElementException;

/**
 * A scheduler that chooses the node with the lowest avg. request duration. 
 * @jmx:mbean name="jboss.web.loadbalancer: service=MinAvgScheduler"
 *            extends="org.jboss.web.loadbalancer.scheduler.AbstractSchedulerMBean"
 *
 * @author Thomas Peuss <jboss@peuss.de>
 * @version $Revision: 1.2 $
 */
public class MinAvgSchedulerService
    extends AbstractScheduler implements MinAvgSchedulerServiceMBean {

  private int index = 0;
  private MinAvgHostComparator comparator=new MinAvgHostComparator();

  public MinAvgSchedulerService() {
  }

  protected Host getNextHost() {
    Host host = null;
    try
    { 
      synchronized (this)
      {
         host=(Host)Collections.min(hostsUp, comparator);
      }
    }
    catch (NoSuchElementException nsee)
    {
       return null;  
    }
    return host;
  }
}

class MinAvgHostComparator implements Comparator
{
   public int compare(Object o1, Object o2)
   {
      Host h1=(Host)o1;
      Host h2=(Host)o2;

      return (h1.getStatistics().getAvgResponseTime()-h2.getStatistics().getAvgResponseTime());
   }
}