import lexeme.Library as Library
import csv
import lexeme.IOHelper as IOHelper
import sys
import os
from tabulate import tabulate

wordgensettings = {}
formrules = {}
phonotactics = {}
formatString = ""


def add():
    '''Interface for addWord().'''
    word = {}
    word['english'] = input("Enter meaning in English: ")
    word['word'] = input("Enter word in conlang: ")

    forms = Library.getFieldOptions("form")
    forms.append("other")

    form = IOHelper.chooseOption("Enter word form",
                                forms)
    if form == "other":
        form = input("Enter new word form: ")

    word['form'] = form

    word = addCustomFields(word)
    Library.addWord(word)
    print("Word saved in database!")


def modify():
    '''Modify an existing word.'''
    try:
        conword = input("Enter word in conlang: ")
        if Library.wordExists(conlang=conword):
            word = Library.findConWord(conword, pop=False)
            outputWord(word)
        else:
            print("Word does not exist")
            return

        keys = list(word.keys())
        keys.remove("id")
        keys.append("NEW")
        keys.append("DELETE")

        another = True

        while another:
            key = IOHelper.chooseOption("Enter field to modify", keys)

            if key == "NEW":
                word = addCustomFields(word, prompt=False)
            elif key == "DELETE":
                keys.remove("NEW")
                keys.remove("DELETE")
                keys.remove("english")
                keys.remove("word")
                key = IOHelper.chooseOption("Enter field to delete", keys)
                keys.remove(key)
                del word[key]

                keys.insert(0, "english")
                keys.insert(0, "word")
                keys.append("NEW")
                keys.append("DELETE")
            else:
                if key in ["word", "english"]:
                    word[key] = input("Enter new value: ")
                else:
                    values = Library.getFieldOptions(key)
                    values.append("other")

                    v = IOHelper.chooseOption("Enter word value",
                                              values)

                    if v == "other":
                        v = input("Enter new value: ")

                    word[key] = v

            another = not IOHelper.yesNo("Finished modifying")

        # Delete word if finished modifying and add new word
        Library.findConWord(conword, pop=True)
        Library.addWord(word)

    except KeyboardInterrupt:
        pass


def listwords():
    '''Interface for listWords().'''
    t = IOHelper.chooseOption("Enter list type", ["all", "field"])

    if t == "field":
        fields = Library.getFields()

        f = IOHelper.chooseOption("Enter desired field", fields)

        options = Library.getFieldOptions(f)

        o = IOHelper.chooseOption("Enter option to list", options)

        l = Library.listWords(t, f, o)
    else:
        l = Library.listWords(t)

    if len(l) > 0:
        outputWordList(l)
    else:
        print("No words to display")


def quit():
    sys.exit(0)


def decline():
    ''' Allows user to select word to decline and declension, then outputs the
    declined word.
    '''
    word = input("Enter word (in conlang) to decline: ")

    try:
        result = Library.findConWord(word)
    except LookupError:
        print("Word not found in database")
        return 1

    prompt = "Select declension"
    dec = IOHelper.createMenu(prompt, Library.getAvailableDeclensions())

    output = Library.declineWord(result, dec)

    outputWord(output, "conlang")


def outputWordList(wordList):
    '''Take a list of words. Output list of words in table.'''
    table = []
    headers = ["English", "Conlang"]

    for word in wordList:
        row = []
        row.append(word["english"])
        row.append(word["word"])
        for item in word:
            if item not in ["english", "word", "id"]:
                row.append(word[item])
        table.append(row)

    for item in wordList[0]:
        if item not in ["english", "word", "id"]:
            headers.append(item.capitalize())

    print("")
    print(tabulate(table, headers=headers))
    print("")


def clearScreen():
    os.system("cls" if os.name == "nt" else "clear")
    lexeme = """
 _
| |    _____  _____ _ __ ___   ___
| |   / _ \ \/ / _ | '_ ` _ \ / _ |
| |__|  __/>  |  __| | | | | |  __/
|_____\___/_/\_\___|_| |_| |_|\___|
                                                """
    print(lexeme)