from treesort import TreeNode
from visualizer import visualize
from random import shuffle

def insert (root, value, key = lambda value: value):
  if not root:
    root = TreeNode()
    root.value = value
  else:
    if value == root.value:
      root.value = value
    else:
      if key(value) < key(root.value):
        root.left = insert(root.left, value, key)
      else:
        root.right = insert(root.right, value, key)
  return root


def make_tree (values, key = lambda word: word):
  tree = None

  for value in values:
    tree = insert(tree, value, key)

  return tree

def clean (word):
  return word.lower().strip(' .,!?-"()[]‘’“”')

def not_empty (word):
  return (word)

if __name__ == '__main__':
  with open('to-sort.txt', 'r') as h:
    text = h.read()
    words = text.split(' ')
    cleaned_words = list(filter(not_empty, map(clean, words)))

    shuffle(cleaned_words)

    visualize(make_tree(cleaned_words), 'text-tree-random')