from operator import methodcaller
class TreeNode(object):

   def __init__(self, name):
      self.name = name
      self.children = []

   def get_name(self):
      return self.name

   def set_children(self, children=None):
       self.children = children
       
   def has_children(self):
       if len(self.children) > 0 :
           return True
       else :
           return False
       
   def add_child(self, child=None):
       self.children.append(child)
       
   def has_child_with_name(self, child_name=None):
       has_child = False 
       for my_child in self.children :
          if my_child.get_name() == child_name :
             has_child = True
             break
       return has_child
   
   def comparekey(self):
       """
       This method allows to compare two nodes of the tree
       main characteristics:
       - case-insensitive
       - places categories above
       """
       if self.has_children():
           # adding a front space to category name places
           # them above...
           return ' '+self.name.lower()
       else:
           return self.name.lower()
   
   def sort_alphabetically(self):
       if self.has_children() : 
           self.children.sort(key=methodcaller('comparekey'))
       for child in self.children :
           child.sort_alphabetically()
   
   def to_json_str(self, node=None):
       self.sort_alphabetically()
       if self.has_children() : 
           json_str = '{"name":"%s"' % self.name
           json_str += ',"children":['
       else:
           json_str = '{"name":"%s"' % self.name
           
       for child in self.children :
           json_str += child.to_json_str() + ','
       if self.has_children() :
           json_str = json_str.rstrip(","); 
           json_str += ']'
       json_str += '}'
       return json_str
