/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.cache.config;

import org.jboss.cache.RegionManager;
import org.jboss.cache.Fqn;
import org.jboss.cache.eviction.EvictionPolicy;
import org.jboss.cache.util.Util;

import java.util.ArrayList;
import java.util.List;

public class EvictionConfig extends ConfigurationComponent
{
   /**
    * The serialVersionUID
    */
   private static final long serialVersionUID = -7979639000026975201L;

   public static final String WAKEUP_INTERVAL_SECONDS = "wakeUpIntervalSeconds";

   public static final int WAKEUP_DEFAULT = 5;

   public static final String EVENT_QUEUE_SIZE = "eventQueueSize";

   public static final String EVICTION_POLICY_CLASS = "policyClass";

   public static final int EVENT_QUEUE_SIZE_DEFAULT = 200000;

   private String defaultEvictionPolicyClass;

   private int wakeupIntervalSeconds = WAKEUP_DEFAULT;

   private int defaultEventQueueSize = EVENT_QUEUE_SIZE_DEFAULT;

   // Dynamic to support runtime adds/removes of regions
   @Dynamic
   private List<EvictionRegionConfig> evictionRegionConfigs;

   public EvictionConfig()
   {
   }

   public EvictionConfig(String defaultEvictionClass)
   {
      setDefaultEvictionPolicyClass(defaultEvictionClass);
   }

   public boolean isValidConfig()
   {
      return (defaultEvictionPolicyClass != null && defaultEvictionPolicyClass.length() > 0)
            || (evictionRegionConfigs != null && evictionRegionConfigs.size() > 0);
   }

   public String getDefaultEvictionPolicyClass()
   {
      return defaultEvictionPolicyClass;
   }

   public void setDefaultEvictionPolicyClass(String defaultEvictionPolicyClass)
   {
      testImmutability("defaultEvictionPolicyClass");
      this.defaultEvictionPolicyClass = defaultEvictionPolicyClass;
   }

   /**
    * Creates an EvictionRegionConfig for the
    * {@link RegionManager.DEFAULT_REGION "_default_"} region using the
    * {@link #getDefaultEvictionPolicyClass(String) default eviction policy class}. Throws a
    * {@link ConfigurationException} if
    * {@link #setDefaultEvictionPolicyClass(String) a default eviction policy class}
    * has not been set.
    *
    * @return an EvictionRegionConfig whose FQN is {@link RegionManager.DEFAULT_REGION}
    *         and whose EvictionPolicyConfig is the default config for the
    *         default eviction policy class.
    * @throws ConfigurationException if a
    *                                {@link #setDefaultEvictionPolicyClass(String) a default eviction policy class}
    *                                has not been set or there is a problem instantiating the configuration.
    */
   public EvictionRegionConfig createDefaultEvictionRegionConfig()
   {
      if (defaultEvictionPolicyClass != null)
      {
         try
         {
            Class<?> cpolicy = Class.forName(defaultEvictionPolicyClass);
            EvictionPolicy policy = (EvictionPolicy) cpolicy.newInstance();
            EvictionRegionConfig erc = new EvictionRegionConfig();
            EvictionPolicyConfig epc = policy.getEvictionConfigurationClass().newInstance();
            erc.setEvictionPolicyConfig(epc);
            erc.setRegionFqn(RegionManager.DEFAULT_REGION);
            return erc;
         }
         catch (Exception e)
         {
            log.error("Unable to create EvictionRegionConfig for default region", e);
            throw new ConfigurationException("Unable to create EvictionRegionConfig for default region", e);
         }
      }
      else
      {
         throw new ConfigurationException("Cannot create EvictionRegionConfig for default region; no defaultEvictionPolicyClass configured");
      }
   }

   public List<EvictionRegionConfig> getEvictionRegionConfigs()
   {
      if (evictionRegionConfigs == null)
      {
         return new ArrayList<EvictionRegionConfig>(1);
      }
      return evictionRegionConfigs;
   }

   public int getDefaultEventQueueSize()
   {
      return defaultEventQueueSize;
   }

   public void setDefaultEventQueueSize(int eventQueueSize)
   {
      this.defaultEventQueueSize = eventQueueSize;
   }

   public void setEvictionRegionConfigs(List<EvictionRegionConfig> evictionRegionConfigs)
   {
      testImmutability("evictionRegionConfigs");

      // Make sure region configs built by MC have the event queue size
      if (evictionRegionConfigs != null)
      {
         for (EvictionRegionConfig cfg : evictionRegionConfigs)
         {
            cfg.setDefaultEventQueueSize(getDefaultEventQueueSize());
         }
      }
      replaceChildConfigs(this.evictionRegionConfigs, evictionRegionConfigs);
      this.evictionRegionConfigs = evictionRegionConfigs;
   }

   public int getWakeupIntervalSeconds()
   {
      return wakeupIntervalSeconds;
   }

   public void setWakeupIntervalSeconds(int wakeupIntervalSeconds)
   {
      testImmutability("wakeupIntervalSeconds");
      this.wakeupIntervalSeconds = wakeupIntervalSeconds;
   }

   @Override
   public boolean equals(Object obj)
   {
      if (this == obj)
         return true;

      if (obj instanceof EvictionConfig)
      {
         EvictionConfig other = (EvictionConfig) obj;
         return (this.wakeupIntervalSeconds == other.wakeupIntervalSeconds)
               && Util.safeEquals(this.defaultEvictionPolicyClass, other.defaultEvictionPolicyClass)
               && Util.safeEquals(this.evictionRegionConfigs, other.evictionRegionConfigs);
      }
      return false;
   }

   @Override
   public int hashCode()
   {
      int result = 17;
      result = 37 * result + wakeupIntervalSeconds;
      result = 37 * result + (defaultEvictionPolicyClass == null ? 0 : defaultEvictionPolicyClass.hashCode());
      result = 37 * result + (evictionRegionConfigs == null ? 0 : evictionRegionConfigs.hashCode());
      return result;
   }

   @Override
   public EvictionConfig clone() throws CloneNotSupportedException
   {
      EvictionConfig clone = (EvictionConfig) super.clone();
      if (evictionRegionConfigs != null)
      {
         List<EvictionRegionConfig> ercs = new ArrayList<EvictionRegionConfig>(evictionRegionConfigs.size());
         for (EvictionRegionConfig erc : evictionRegionConfigs)
         {
            ercs.add(erc.clone());
         }
         clone.setEvictionRegionConfigs(ercs);
      }
      return clone;
   }


   /**
    * Returns the <code>EvictionRegionConfig</code> coresponding to given region fqn, or <code>null</code> if no
    * match is found.
    */
   public EvictionRegionConfig getEvictionRegionConfig(String region)
   {
      Fqn<String> fqn = Fqn.fromString(region);
      for (EvictionRegionConfig evConfig : getEvictionRegionConfigs())
      {
         if (evConfig.getRegionFqn().equals(fqn))
         {
            return evConfig;
         }
      }
      return null;
   }
}
