package kz.cafe.logs;


import java.util.*;



public class LogTreeFormatter{

   private Node nodeRoot;


   private int iPadding = 6;



   public LogTreeFormatter(String sName){
      this.nodeRoot = new Node(sName);
   }



   public LogTreeFormatter(String sName, int iPadding){
      this.nodeRoot = new Node(sName);
      this.iPadding = iPadding;
   }





   public Node getRoot(){
      return nodeRoot;
   }







   public String toString(){
      StringBuilder sbResult = new StringBuilder();

      sbResult.append(printNode(0, nodeRoot));

      return sbResult.toString();
   }






   private StringBuilder printNode(int offset, Node node){
      StringBuilder sb = new StringBuilder();

      Node nodeParent = node.parent;

      for(int f = 0; f < offset; f++){
         if(f > 0 && f % iPadding == 0){
            if(nodeParent.last == true){
               sb.insert(0, " ");
            }
            else {
               sb.insert(1, "|");
            }

            nodeParent = nodeParent.parent;
         }
         else {
            sb.insert(0, " ");
         }
      }
      sb.append("|-" + node.getName() + "\n");


      for(Iterator<Node> it = node.getChildren().iterator(); it.hasNext(); ){
         Node nodeChild = it.next();

         sb.append(printNode(offset + iPadding, nodeChild));
      }


      return sb;
   }







   public class Node{

      private final List<Node> children = new ArrayList<Node>();

      private final String name;
      private Node parent = null;
      private boolean last = true;




      public Node(String name){
         this.name = name;
      }





      public Node addNode(Number nName){
         return addNode("" + nName);
      }





      public Node addNode(String sName){
         Node node = new Node(sName);
         node.parent = this;

         for(Node nodeChild : children){
            nodeChild.last = false;
         }

         children.add(node);
         return node;
      }





      public List<Node> getChildren(){
         return children;
      }





      public String getName(){
         return name;
      }
   }
}
