/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.optimistic;

import org.jboss.cache.Fqn;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Contains a mapping of Fqn to {@link WorkspaceNode}s.
 * Each entry corresponds to a series of changed nodes within the transaction.
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @author Steve Woodcock (<a href="mailto:stevew@jofti.com">stevew@jofti.com</a>)
 */
public class TransactionWorkspaceImpl<K, V> implements TransactionWorkspace<K, V>
{

   private Map<Fqn, WorkspaceNode<K, V>> nodes;
   private boolean versioningImplicit = true;

   public TransactionWorkspaceImpl()
   {
      nodes = new HashMap<Fqn, WorkspaceNode<K, V>>();
   }

   /**
    * Returns the nodes.
    */
   public Map<Fqn, WorkspaceNode<K, V>> getNodes()
   {
      return nodes;
   }

   public void clearNodes()
   {
      nodes.clear();
   }

   /**
    * Sets the nodes.
    */
   public void setNodes(Map<Fqn, WorkspaceNode<K, V>> nodes)
   {
      this.nodes = nodes;
   }

   public WorkspaceNode<K, V> getNode(Fqn fqn)
   {
      return nodes.get(fqn);
   }

   public void addNode(WorkspaceNode<K, V> node)
   {
      nodes.put(node.getFqn(), node);
   }

   public WorkspaceNode<K, V> removeNode(Fqn fqn)
   {
      return nodes.remove(fqn);
   }

   public SortedMap<Fqn, WorkspaceNode<K, V>> getNodesAfter(Fqn fqn)
   {
      SortedMap<Fqn, WorkspaceNode<K, V>> sm = new TreeMap<Fqn, WorkspaceNode<K, V>>();
      sm.putAll(nodes);
      return sm.tailMap(fqn);
   }

   public boolean isVersioningImplicit()
   {
      return versioningImplicit;
   }

   public void setVersioningImplicit(boolean versioningImplicit)
   {
      this.versioningImplicit = versioningImplicit;
   }

   public boolean hasNode(Fqn fqn)
   {
      return nodes.containsKey(fqn);
   }

   /**
    * Returns debug information.
    */
   @Override
   public String toString()
   {
      return "Workspace nodes=" + nodes;
   }
}
