/*
 * 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 current connection count. It
 * takes the loadbalance factor (lbFactor) into account. The node with the higher lbFactor
 * gets more requests.
 * 
 * @jmx:mbean name="jboss.web.loadbalancer: service=WeightedLeastConnectionScheduler"
 *            extends="org.jboss.web.loadbalancer.scheduler.AbstractSchedulerMBean"
 *
 * @author Thomas Peuss <jboss@peuss.de>
 * @version $Revision: 1.1 $
 */
public class WeightedLeastConnectionSchedulerService 
    extends AbstractScheduler implements WeightedLeastConnectionSchedulerServiceMBean {

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

  public WeightedLeastConnectionSchedulerService() {
  }

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

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

      return ((h1.getCurrentConnections()/h1.getLbFactor())-(h2.getCurrentConnections()/h2.getLbFactor()));
   }
}