/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.varia.stats;


/**
 * @author <a href="mailto:alex@jboss.org">Alexey Loubyansky</a>
 * @version <tt>$Revision: 1.2 $</tt>
 */
public abstract class AbstractStatisticalItem
   implements StatisticalItem
{
   protected final String name;
   protected String value;
   private int count = 1;
   private int minCountPerTx = Integer.MAX_VALUE;
   private int maxCountPerTx;
   private int mergedItemsTotal = 1;

   public AbstractStatisticalItem(String name)
   {
      this.name = name;
   }

   public String getName()
   {
      return name;
   }

   public String getValue()
   {
      return value;
   }

   public int getMinCountPerTx()
   {
      return minCountPerTx == Integer.MAX_VALUE ? count : minCountPerTx;
   }

   public int getMaxCountPerTx()
   {
      return maxCountPerTx == 0 ? count : maxCountPerTx;
   }

   public int getCount()
   {
      return count;
   }

   public void add(StatisticalItem item)
   {
      if(!getName().equals(item.getName()))
      {
         throw new IllegalArgumentException("Can't merge statistical items with different names: " +
            getName() + " and " + item.getName());
      }

      this.count += item.getCount();
   }

   public void merge(StatisticalItem item)
   {
      add(item);

      ++mergedItemsTotal;

      int count = item.getCount();
      if(count > maxCountPerTx)
      {
         maxCountPerTx = count;
      }

      if(count < minCountPerTx)
      {
         minCountPerTx = count;
      }
   }

   public void mergeNull()
   {
      //++mergedItemsTotal;
      minCountPerTx = 0;
   }

   public int getMergedItemsTotal()
   {
      return mergedItemsTotal;
   }
}