package org.jboss.cache.config;

import org.jboss.cache.xml.XmlHelper;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * A configuration component where the implementation class can be specified, and comes with its own set of properties.
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @since 2.2.0
 */
public abstract class PluggableConfigurationComponent extends ConfigurationComponent
{
   protected String className;
   protected Properties properties;

   public String getClassName()
   {
      return className;
   }

   public void setClassName(String className)
   {
      if (className == null || className.length() == 0) return;
      testImmutability("className");
      this.className = className;
   }

   public Properties getProperties()
   {
      return properties;
   }

   public void setProperties(Properties properties)
   {
      testImmutability("properties");
      this.properties = properties;
   }

   public void setProperties(String properties) throws IOException
   {
      if (properties == null) return;

      testImmutability("properties");
      // JBCACHE-531: escape all backslash characters
      // replace any "\" that is not preceded by a backslash with "\\"
      properties = XmlHelper.escapeBackslashes(properties);
      ByteArrayInputStream is = new ByteArrayInputStream(properties.trim().getBytes("ISO8859_1"));
      this.properties = new Properties();
      this.properties.load(is);
      is.close();
   }

   public boolean equals(Object o)
   {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      PluggableConfigurationComponent that = (PluggableConfigurationComponent) o;

      if (className != null ? !className.equals(that.className) : that.className != null) return false;
      if (properties != null ? !properties.equals(that.properties) : that.properties != null) return false;

      return true;
   }

   public int hashCode()
   {
      int result;
      result = (className != null ? className.hashCode() : 0);
      result = 31 * result + (properties != null ? properties.hashCode() : 0);
      return result;
   }

   @Override
   public String toString()
   {
      return getClass().getSimpleName() + " {className = " + className +
            ", properties=" + properties + "}";
   }

   @Override
   public PluggableConfigurationComponent clone() throws CloneNotSupportedException
   {
      PluggableConfigurationComponent clone = (PluggableConfigurationComponent) super.clone();
      if (properties != null) clone.properties = (Properties) properties.clone();
      return clone;
   }
}
