import numpy as np

class TrieNode:
	def __init__(self):
		self.children = np.array([None for i in range(27)]) # el alfabeto inglés tiene 27 caracteres
		self.info = None

	def print_all_nodes(self):
		if self.info != None:
			print(self.info)
		for child in self.children:
			if child != None:
				child.print_all_nodes()



class Trie:
	def __init__(self):
		self.head = TrieNode()


	def insert(self, s):
		s = s.lower()
		if not s.isalpha():
			print('only alphabetic strings allowed')
			return
		i = 0
		current_node = self.head
		while i < len(s):
			index = ord(s[i]) - ord('a') #ord entrega el valor numérico (ASCII) del caracter
			if current_node.children[index] == None:
				current_node.children[index] = TrieNode()
			current_node = current_node.children[index]
			i += 1
		current_node.info = s

	def search(self, s):
		s = s.lower()
		if not s.isalpha():
			print('only alphabetic strings allowed')
			return
		i = 0
		current_node = self.head
		while i < len(s):
			index = ord(s[i]) - ord('a') #ord entrega el valor numérico (ASCII) del caracter
			if current_node.children[index] == None:
				return False
			current_node = current_node.children[index]
			i += 1
		return current_node.info == s

	def buscar_prefijo(self, prefix):
		prefix = prefix.lower()
		if not prefix.isalpha():
			print('only alphabetic strings allowed')
			return
		i = 0
		current_node = self.head
		while i < len(prefix):
			index = ord(prefix[i]) - ord('a') #ord entrega el valor numérico (ASCII) del caracter
			current_node = current_node.children[index]
			if current_node is None:
				print('No words starting with prefix ', prefix)
				return
			i+=1

		current_node.print_all_nodes()


	def print_all_nodes(self):
		self.head.print_all_nodes()


trie = Trie()

"""trie.insert('asa')
trie.insert('asado')
trie.insert('asaito')
trie.insert('pan')
trie.insert('pancito')
trie.insert('panaderia')
print(trie.search('panaderia'))
print(trie.search('pancito'))

trie.print_all_nodes()"""

filepath = 'words_alpha.txt'
with open(filepath) as fp:
   line = fp.readline()
   while line:
       trie.insert(line.rstrip())
       line = fp.readline()

print('ingrese un prefijo (o - para salir)')
x = input()
while(x != '-'):
	trie.buscar_prefijo(x)
	print('ingrese un prefijo (o - para salir)')
	x = input()
