import csv

alphabet = [["A", ".-"],
            ["B", "-..."],
            ["C", "-.-."],
            ["D", "-.."],
            ["E", "."],
            ["F", "..-."],
            ["G", "--."],
            ["H", "...."],
            ["I", ".."],
            ["J", ".---"],
            ["K", "-.-"],
            ["L", ".-.."],
            ["M", "--"],
            ["N", "-."],
            ["O", "---"],
            ["P", ".--."],
            ["Q", "--.-"],
            ["R", ".-."],
            ["S", "..."],
            ["T", "-"],
            ["U", "..-"],
            ["V", "...-"],
            ["W", ".--"],
            ["X", "-..-"],
            ["Y", "-.--"],
            ["Z", "--.."],
            ["Ä", ".-.-"],
            ["Ö", "---."],
            ["Ü", "..--"],
            ["ẞ", "...--.."],
            [" ", " "],
            ["0", "-----"],
            ["1", ".----"],
            ["2", "..---"],
            ["3", "...--"],
            ["4", "....-"],
            ["5", "....."],
            ["6", "-...."],
            ["7", "--..."],
            ["8", "---.."],
            ["9", "----."]]

morse_cipher = "..-..--..-......-"

def latin_to_morse(expression, delimiter=""):  # expression: zu übersetzendes Wort
    result = ""
    for letter in expression:
        for latin, morse in alphabet:
            if letter == latin:
                result += morse
                result += delimiter
    return result


def guess_chars(morse_text, plain_text=""):
    def recursion(morse_text, plain_text=""):  # morse_text = zu zerlegender Morse-Salat
        if morse_text == "":
            char_guesses.append(plain_text)
        else:
            for latin, morse in alphabet:
                if morse == morse_text[0:len(morse)]:
                    recursion(morse_text[len(morse):len(morse_text)], (plain_text + latin))

    char_guesses = []
    recursion(morse_text, plain_text)
    return char_guesses


def guess_vocabs(query, phrase=""):  # query = zu zerlegender Buchstabensalat
    if query == "":
        vocab_guesses.append(phrase)
    else:
        for vocab in dictionary:
            if vocab == query[0:len(vocab)]:
                guess_vocabs(query[len(vocab):len(query)], (phrase + vocab + " "))


def wordlist_to_morse(dictionary_latin):  # dictionary_latin = einsprachiges Wörterbuch (Wörterbuch)
    result = []
    for entry in dictionary_latin:
        result.append([latin_to_morse(entry), entry])
    return result


def guess_vocabs_BUT_AWESOME(cipher, dictionary, min_vocab_len = 0, max_word_count = 0):  # cipher: zu entschlüsselnde Chiffre, dictionary: Wortliste im Morsecode
    length = len(cipher)
    if max_word_count == 0: max_word_count = length          # Bei Standardwert 0 wird max_word_count so hoch gesetzt, dass es de facto keine Einschränkung macht.
    phrase_kit = [[] for x in range(length + 2, 0, -1)]
    phrase_kit[length + 1] = " "
    print(phrase_kit)
    for i in range(length, 0, -1):  # vom hintersten Buchstaben an nach vorne wird die Chiffre in immer längere Schnipsel gehackt
        query = cipher[i - 1:length]  # query: Schnipsel der Chiffre wird auf sinnvolle Worte getestet
        for vocab in dictionary:
            if vocab[0] == query[0:len(vocab[0])] \
                    and len(vocab[1]) >= min_vocab_len:  # wird ein passendes Wort gefunden und gibt es im phrase-kit Worte, die das gefundene Wort zur Länge des zu prüfenden Wortes ergänzen...
                print("i = ", i, " Appending to ", vocab[1], " len = ", len(vocab[1]))
                for phrase in phrase_kit[i + len(vocab[0])]:
                    if phrase.count(" ") <= max_word_count:
                        phrase_kit[i].append(vocab[1] + " " + phrase)
    return phrase_kit


def deciphering_1():
    char_guesses = []
    guess_chars(morse_cipher)
    print("Chars guessed. char_guesses complete.")

    guess_list_len = len(char_guesses)
    for index, word in enumerate(char_guesses):
        print("(", index, "/", guess_list_len, ") - ", word, "...", end="")
        vocab_guesses = []
        guess_vocabs(word)
        print("\r", end="")
        if vocab_guesses:
            print("Found something: ", vocab_guesses)


dictDE_file = open("wordlist-german.txt", "r", encoding="utf-8")
dictEN_file = open("wordlist-english.txt", "r", encoding="utf-8")
dictEN_short_file = open("corncob_caps.txt", "r", encoding="utf-8")

reader = csv.reader(dictDE_file)
dictDE = [row[0].upper() for row in reader]
reader = csv.reader(dictEN_file)
dictEN = [row[0].upper() for row in reader]
reader = csv.reader(dictEN_short_file)
dictEN_short = [row[0].upper() for row in reader]
dictionary = dictEN_short
#dictionary = ["FEMINIST", "TERESA", "INA", "ES", "MIT", "SEIT", "ID"]

dictMORSE = wordlist_to_morse(dictionary)
print("dictMORSE erstellt")
phrase_kit = guess_vocabs_BUT_AWESOME(morse_cipher, dictMORSE, max_word_count=3)
for result in phrase_kit[1]:
    print(result)


