import sys
import time
import random

# hard coded, default is 1000  
# fix naming of variables for the unix dict program 
sys.setrecursionlimit(1000000000)

corpus = []
with open('words') as f:
    corpus = f.readlines()

corpus = [word.strip() for word in corpus]

class word_leaf:
    def __init__(self,letter,word):
        self.leftAlphabet = None
        self.rightAlphabet = None
        self.letter = letter
        self.word = word

def print2DUtil_flat(root, space, interval, COUNT):
    if (root == None) :
        return
    
    space += COUNT[0]
    print2DUtil_flat(root.rightAlphabet, space, interval, COUNT)
    
    print()
    
    for i in range(COUNT[0], space):
        print(end = " ")
        
    print(root.word)
    
    for i in range(COUNT[0], space):
        print(end = " ")

    time.sleep(interval)

    print2DUtil_flat(root.leftAlphabet, space,interval, COUNT)

def print2D(root, interval):
    print2DUtil_flat(root, 0, interval, COUNT=[10])

def grep_first_letter(word):
    first_letter = word[0]
    return first_letter

def insert_leaf(root,word):
    letter = grep_first_letter(word)
    new_leaf = word_leaf(letter,word)
    x = root
    y = None

    while (x != None):
        y = x
        if (letter < x.letter):
            x = x.leftAlphabet
        else:
            x = x.rightAlphabet

    if (y == None):
        y = new_leaf

    elif (letter < y.letter):
        y.leftAlphabet = new_leaf

    else:
        y.rightAlphabet = new_leaf
        
    return y

def ask_input():
    interval = int(input("Enter growth rate value for tree in seconds: "))
    return interval

if __name__ == "__main__":

    root = None
    random_word = random.choice(corpus)
    print("Taking some time to process corpus...")
    root = insert_leaf(root, random_word)
    corpus.remove(random_word)
    len_list = (len(corpus))
    while len_list > 0:
        random_word = random.choice(corpus)
        insert_leaf(root,random_word)
        corpus.remove(random_word)
        len_list -= 1
    interval = ask_input()
    print2D(root, interval)

