from curses import wrapper
from collections import Counter as Bag
import curses
from copy import copy
words = map(str.strip, open("basiswoorden-gekeurd.txt").readlines())
words = sorted(list(words), key=len)

COLS=None

def word_in_letters(word, letters):
    c = list(letters)
    for letter in word:
        if letter in c:
            c.remove(letter)
        else:
            return False
    return True

def matches(letters):
    return [word for word in words if word_in_letters(word, letters)]

def write_str_centered(scr, y, string, attr=None):
    pos = (COLS // 2) - len(string)//2
    if attr:
        scr.addstr(y, pos, string, attr)
    else:
        scr.addstr(y, pos, string)

def print_times_tables(window):
    window.erase()

    for i in range(1, 40):
        window.addstr(i, 0, "%d\t%d\t%d" % (i, 25*i, 75*i))
    window.refresh()

def main(stdscr):
    global COLS
    curses.noecho()
    curses.cbreak()
    stdscr.clear()

    x,y = curses.COLS, curses.LINES
    COLS = x

    inputwin = curses.newwin(y-6, x-31, 12, 0)
    inputwin.keypad(True)

    buffer = ""
    offset = 0

    write_str_centered(stdscr, 10, "Enter the letters here", attr=curses.A_BOLD)
    stdscr.refresh()

    max_items = y-15

    statwin = curses.newwin(2, 15, 2, x-16)

    ttwin = curses.newwin(y-6, 50, 4, x-31)

    while True:
        inputwin.erase()
        statwin.erase()
        for n, i in enumerate(matches(buffer)[-max_items + offset:][:max_items]):
            write_str_centered(inputwin, 3+n, i)

        write_str_centered(inputwin, 0, buffer, attr=curses.A_UNDERLINE)

        inputwin.refresh()
        statwin.addstr(0, 0, "Offset: %d" % offset)
        statwin.refresh()

        print_times_tables(ttwin)

        key = inputwin.getkey()
        try:
            key = key.decode('utf-8')
        except:
            pass
        if (key == "KEY_DOWN"):
            offset = offset + 1
        elif (key == "KEY_UP"):
            offset = offset - 1
        elif (key == "KEY_BACKSPACE"):
            buffer = buffer[:len(buffer)-1]
        elif len(key) == 1:
            try:
                buffer += key
            except:
                curses.endwin()
                print("Key was: ")
                print(key)

try:
    main(curses.initscr())
finally:
    curses.endwin()
