#include"mkf_node.hpp"




Node::
Node(const Definition*  def, int  c):
parent(nullptr),
depth(0),
definition(def),
character(c)
{
}


Node::
Node(Node&&  rhs):
parent(rhs.parent),
depth(rhs.depth),
definition(rhs.definition),
character(rhs.character),
children(std::move(rhs.children))
{
}


Node::
~Node()
{
    for(auto&  nd: children)
    {
      delete nd;
    }
}


void
Node::
append(Node*  child)
{
    if(child)
    {
      child->depth = depth+1;

      child->parent = this;

      children.emplace_back(child);
    }
}


void
Node::
omit()
{
    while(children.size() == 1)
    {
      auto  unique_child = children.front();

      definition = unique_child->definition;
      character  = unique_child->character;

      children = std::move(unique_child->children);

        for(auto  child: children)
        {
          child->parent =    this;
          child->depth  = depth+1;
        }


      delete unique_child;
    }


  omit_children_all();
}


void
Node::
omit_children_all()
{
    for(auto  child: children)
    {
      child->omit();
    }
}


void
Node::
print(int  indent) const
{
    if(children.empty())
    {
      iputc(indent,character);
    }

  else
    {
      iput(indent);

        if(definition)
        {
          printf("%s",definition->get_identifier().get_buffer());
        }


      printf("{\n");

        for(auto  child: children)
        {
          child->print(indent+1);

          printf("\n");
        }


      iprintf(indent,"}\n");
    }
}



