package org.jboss.cache.commands.write;

import org.jboss.cache.DataContainer;
import org.jboss.cache.Fqn;
import org.jboss.cache.commands.VersionedDataCommand;
import org.jboss.cache.commands.read.AbstractDataCommand;
import org.jboss.cache.notifications.Notifier;
import org.jboss.cache.optimistic.DataVersion;
import org.jboss.cache.transaction.GlobalTransaction;

/**
 * Base version of {@link org.jboss.cache.commands.DataCommand} which handles common behaviour
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @since 2.2.0
 */
public abstract class AbstractVersionedDataCommand extends AbstractDataCommand implements VersionedDataCommand
{
   protected Notifier notifier;

   protected DataVersion dataVersion;
   protected GlobalTransaction globalTransaction;

   public void initialize(Notifier notifier, DataContainer dataContainer)
   {
      this.notifier = notifier;
      this.dataContainer = dataContainer;
   }

   public DataVersion getDataVersion()
   {
      return dataVersion;
   }

   public void setDataVersion(DataVersion dataVersion)
   {
      this.dataVersion = dataVersion;
   }

   public GlobalTransaction getGlobalTransaction()
   {
      return globalTransaction;
   }

   public void setGlobalTransaction(GlobalTransaction globalTransaction)
   {
      this.globalTransaction = globalTransaction;
   }

   public boolean isVersioned()
   {
      return dataVersion != null;
   }

   // basic implementations
   @Override
   public Object[] getParameters()
   {
      if (isVersioned())
         return new Object[]{fqn, dataVersion};
      else
         return new Object[]{fqn};
   }

   // basic implementations
   @Override
   public void setParameters(int commandId, Object[] args)
   {
      fqn = (Fqn) args[0];
      if (isVersionedId(commandId)) dataVersion = (DataVersion) args[1];
   }

   protected abstract boolean isVersionedId(int id);

   @Override
   public boolean equals(Object o)
   {
      if (!super.equals(o)) return false;
      AbstractVersionedDataCommand that = (AbstractVersionedDataCommand) o;
      return !(fqn != null ? !fqn.equals(that.fqn) : that.fqn != null);
   }

   @Override
   public int hashCode()
   {
      return 31 * super.hashCode() + (dataVersion != null ? dataVersion.hashCode() : 0);
   }
}