package commons.script;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import basics.utl.SUtl;
import basics.utl.SysUtl;

public class XNode
{
final static String KB            = "";
String              namespace     = KB;   // <keyboard> | filename | namespace makro value
int                 lineNo        = -1;   // number of line in the original source file or -1 if none
protected XNode     parent        = null;
protected boolean   expanded      = false;
List<XNode>         straightNodes = null;
List<XNode>         altNodes      = null;
boolean             repeat        = false;
protected boolean   onElse        = false;
Map<String, XNode>  labelMap      = null;

public XNode getRoot()
{
   return parent == null ? this : parent.getRoot();
}

protected void addNodeLabel(String label)
{
   XNode root = getRoot();
   if(root.labelMap == null)
      root.labelMap = new HashMap<String, XNode>();
   SysUtl.trace("Register % with % under root %", this, label, root);
   root.labelMap.put(label, this);
}

protected XNode getLabeledNode(String label)
{
   XNode root = getRoot();
   if(root.labelMap == null)
      root.labelMap = new HashMap<String, XNode>();
   return root.labelMap.get(label);
}

public void onElse()
{
   onElse = true;
}

XNode addNode(XNode p)
{
   p.parent = this;
   if(!onElse)
   {
      if(straightNodes == null)
         straightNodes = new ArrayList<XNode>();
      straightNodes.add(p);
   }
   else
   {
      if(altNodes == null)
         altNodes = new ArrayList<XNode>();
      altNodes.add(p);
   }
   return this;
}

XNode addChild(XNode p)
{
   p.parent = this;
   if(!onElse)
   {
      if(straightNodes == null)
         straightNodes = new ArrayList<XNode>();
      straightNodes.add(p);
   }
   else
   {
      if(altNodes == null)
         altNodes = new ArrayList<XNode>();
      altNodes.add(p);
   }
   return p;
}

XNode getParent()
{
   return parent;
}

public String toString()
{
   return SUtl.sprint("%@%[%%%]", getClass().getSimpleName(), Integer.toHexString(hashCode()),
      parent == null ? "ROOT" : "", straightNodes == null ? "" : "+N", repeat ? " XR" : "");
}
}
