/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.pojo.test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Test class for PojoCache for circular references.
 * Link is a POJO that will be instrumentet with CacheFieldInterceptor
 *
 * @version $Revision: 4456 $
 *          <p>Below is the annotation that signifies this class is "prepared" under JBossAop. This is used in
 *          conjunction with a special jboss-aop.xml (supplied by JBossCache). In addition, this is JDK1.4 style,
 *          so a annoc Ant build target is needed to pre-compile it.</p>
 *          <p>To use this approach, just apply this line to your pojo and run annoc (and possibly aopc).</p>
 */
// We are using JDK1.5 annotation.
@org.jboss.cache.pojo.annotation.Replicable
public class NodeManager
{
   private TestNode rootNode_;

   private Map<String, TestNode> nodeMap_ = new HashMap<String, TestNode>();

   public NodeManager()
   {
   }

   public void setRootNode(String rdn)
   {
      this.rootNode_ = new TestNode();
      rootNode_.setNodeFDN(rdn);
      rootNode_.setNodeRDN(rdn);

      registMap(rootNode_);
   }

   public void addNode(String parentFdn, String rdn)
   {
      TestNode parent = findNode(parentFdn);
      if (parent != null)
      {
         TestNode node = new TestNode();
         node.setNodeFDN(parentFdn + "." + rdn);
         node.setNodeRDN(rdn);

         node.setParentNode(parent);
         parent.addChildNode(node);

         registMap(node);
      }
   }

   public TestNode findNode(String fdn)
   {
      return nodeMap_.get(fdn);
   }

   private void registMap(TestNode node)
   {
      this.nodeMap_.put(node.getNodeFDN(), node);
   }

   public void printNodes()
   {
      printNode(rootNode_, "");
   }

   private void printNode(TestNode node, String prefix)
   {
      System.out.println(prefix + node.getNodeRDN());

      String childPrefix = prefix + " + ";
      List<TestNode> children = node.getChildren();
      int size = children.size();
      for (int idx = 0; idx < size; idx++)
      {
         TestNode child = (TestNode) children.get(idx);
         printNode(child, childPrefix);
      }
   }

}
