package org.jboss.cache.commands.write;

import org.jboss.cache.Fqn;
import org.jboss.cache.InvocationContext;
import org.jboss.cache.NodeSPI;
import org.jboss.cache.commands.ReversibleCommand;
import org.jboss.cache.commands.Visitor;
import org.jboss.cache.commands.read.AbstractDataCommand;
import org.jboss.cache.transaction.GlobalTransaction;

import java.util.LinkedList;
import java.util.List;

/**
 * Command that creates a node.  Primarily to be used as an undo command for removing nodes.
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @since 2.2.0
 */
public class CreateNodeCommand extends AbstractDataCommand implements ReversibleCommand
{
   public static final int METHOD_ID = 48;
   private final List<Fqn> newlyCreated = new LinkedList<Fqn>();

   public CreateNodeCommand(Fqn fqn)
   {
      this.fqn = fqn;
      newlyCreated.add(fqn);
   }

   public CreateNodeCommand()
   {
   }

   public int getCommandId()
   {
      return METHOD_ID;
   }

   public void setGlobalTransaction(GlobalTransaction gtx)
   {
      // no op
   }

   public GlobalTransaction getGlobalTransaction()
   {
      return null;
   }

   /**
    * Creates a node in the cache, specified by the given Fqn.
    */
   public Object perform(InvocationContext ctx) 
   {
      Object[] results = dataContainer.createNodes(fqn);
      List<NodeSPI> created = (List<NodeSPI>) results[0];

      boolean foundFqn = false;
      if (!created.isEmpty())
      {
         for (NodeSPI n : created)
         {
            if (fqn.equals(n.getFqn())) foundFqn = true;
            newlyCreated.add(n.getFqn());
         }
      }
      if (newlyCreated != null && !foundFqn) newlyCreated.remove(fqn);

      return results[1];
   }

   public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
   {
      return visitor.visitCreateNodeCommand(ctx, this);
   }

   public void rollback()
   {
      if (newlyCreated != null)
      {
         for (Fqn f : newlyCreated) dataContainer.removeFromDataStructure(f, true);
      }
   }

   @Override
   public String toString()
   {
      return "CreateNodeCommand{" +
            "fqn=" + fqn +
            ", newlyCreated=" + newlyCreated +
            '}';
   }

   List<Fqn> getNewlyCreated()
   {
      return newlyCreated;
   }
}
