""" 
Converses using Markov Model

"""
import nltk
from database import database
import os

"""
Creates database.
Collects data from Brown Corpus in the NLTK package.
"""

data = database()
f = open(os.getcwd() + "/Text_Files/data.txt", "w")    
for word in data:
    f.write(word + " ")
f.close()
del f

"""
Generates a word given a seed word by using the Markov model
"""
def Markov_generate_unigram(seed):
    seed = ''.join(seed)
    counter = 1
    next_word_list = []
    for i in data:
        if seed == i:
            next_word_list.append(data[counter])
        counter += 1
    if len(next_word_list) == 0:
        return nltk.bigrams(["you", "are"])
    cfdist = nltk.FreqDist(next_word_list)
    next_word = cfdist.max()
    return nltk.bigrams([seed, next_word])
    
"""
Generates bigrams using the Markov process
"""
def Markov_generate_bigrams(tuples):
    counter = 1
    index_list = []
    data_bigrams = nltk.bigrams(data)
    for i in data_bigrams:
        if tuples == i:
            index_list.append(data[counter+1])
        counter += 1    
    return index_list

"""
Receives a sentence.
Returns another one, which was generated by the Markov process.
"""
def converse(raw_sentence):
    words_in_sent = raw_sentence.split()
    if len(words_in_sent) > 1:
        bigrams = nltk.bigrams(words_in_sent)
    
    else:
        bigrams = Markov_generate_unigram(words_in_sent)
    
    text_len = 20
    generated_lines = []

    for tuples in bigrams:
        line = []
        line.append(''.join(tuples[0]).title()+" ")
        line.append(''.join(tuples[1])+" ")
        for i in range(text_len):
            next_words = Markov_generate_bigrams(tuples)
            if not next_words: 
                break
            cfdist = nltk.FreqDist(next_words)
            next_word = cfdist.max()
            line.append(next_word+" ")
            new_tuple = (tuples[1], next_word)
            del tuples
            tuples = new_tuple
    
        generated_lines.append(line)

    longest_line = ''
    for line in generated_lines:
        
        stri = ''.join(line)
        if "." in stri:
            truncate_char = "."
        elif "?" in stri:
            truncate_char = "?"
        elif "!" in stri:
            truncate_char = "!"
        try:
            stri = stri[:stri.index(truncate_char)]
        except:
            pass
        if len(line) > len(longest_line):
            longest_line = stri.strip()+"."
    
    return longest_line
