import random
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
import pickle as pk
use_cuda = torch.cuda.is_available()
SOS_token = 0
EOS_token = 1
MAX_LENGTH = 80
class Dataset:
    def __init__(self, name):
        self.name = name
        self.word2index = {}
        self.word2count = {}
        self.index2word = {0: "SOS", 1: "EOS"}
        self.n_words = 2  # Count SOS and EOS

    def addSentence(self, sentence):
        for word in sentence.split(' '):
            self.addWord(word)

    def addWord(self, word):
        if word not in self.word2index:
            self.word2index[word] = self.n_words
            self.word2count[word] = 1
            self.index2word[self.n_words] = word
            self.n_words += 1
        else:
            self.word2count[word] += 1

def dataclean(training_data):
    input_data = Dataset('input')
    output_data = Dataset('ouput')
    for pair in training_data:
        input_data.addSentence(pair[0])
        output_data.addSentence(pair[1])
    return input_data, output_data, input_data.n_words, output_data.n_words

class EncoderRNN(nn.Module):
    def __init__(self, input_size, hidden_size, n_layers=1):
        super(EncoderRNN, self).__init__()
        self.n_layers = n_layers
        self.hidden_size = hidden_size

        if use_cuda:
           self.embedding = nn.Embedding(input_size, hidden_size).cuda()
           self.gru = nn.GRU(hidden_size, hidden_size).cuda()
        else:
           self.embedding = nn.Embedding(input_size, hidden_size)
           self.gru = nn.GRU(hidden_size, hidden_size)

    def forward(self, input, hidden):
        embedded = self.embedding(input).view(1, 1, -1)
        output = embedded
        for i in range(self.n_layers):
            output, hidden = self.gru(output, hidden)
            output = output.cuda() if use_cuda else output
            hidden = hidden.cuda() if use_cuda else output
        return output, hidden

    def initHidden(self):
        result = Variable(torch.zeros(1, 1, self.hidden_size))
        if use_cuda:
           return result.cuda()
        return result

class AttnDecoderRNN(nn.Module):
    def __init__(self, hidden_size, output_size, n_layers=1, dropout_p=0.1, max_length=MAX_LENGTH):
        super(AttnDecoderRNN, self).__init__()
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.n_layers = n_layers
        self.dropout_p = dropout_p
        self.max_length = max_length
        if use_cuda:

           self.embedding = nn.Embedding(self.output_size, self.hidden_size).cuda()
           self.attn = nn.Linear(self.hidden_size * 2, self.max_length).cuda()
           self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size).cuda()
           self.dropout = nn.Dropout(self.dropout_p).cuda()
           self.gru = nn.GRU(self.hidden_size, self.hidden_size).cuda()
           self.out = nn.Linear(self.hidden_size, self.output_size).cuda()
        else:
           self.embedding = nn.Embedding(self.output_size, self.hidden_size)
           self.attn = nn.Linear(self.hidden_size * 2, self.max_length)
           self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)
           self.dropout = nn.Dropout(self.dropout_p)
           self.gru = nn.GRU(self.hidden_size, self.hidden_size)
           self.out = nn.Linear(self.hidden_size, self.output_size)

    def forward(self, input, hidden, encoder_output, encoder_outputs):
        embedded = self.embedding(input).view(1, 1, -1)
        embedded = self.dropout(embedded)

        attn_weights = F.softmax(
            self.attn(torch.cat((embedded[0], hidden[0]), 1)))
        attn_weights = attn_weights.cuda() if use_cuda else attn_weights
        attn_applied = torch.bmm(attn_weights.unsqueeze(0),
                                 encoder_outputs.unsqueeze(0))
        attn_applied = attn_applied.cuda() if use_cuda else attn_applied

        output = torch.cat((embedded[0], attn_applied[0]), 1)
        output = output.cuda() if use_cuda else output
        output = self.attn_combine(output).unsqueeze(0)

        for i in range(self.n_layers):
            output = F.relu(output)
            output = output.cuda() if use_cuda else output
            output, hidden = self.gru(output, hidden)

        output = F.log_softmax(self.out(output[0]))
        output = output.cuda() if use_cuda else output
        return output, hidden, attn_weights

    def initHidden(self):
        result = Variable(torch.zeros(1, 1, self.hidden_size))
        if use_cuda:
           return result.cuda()
        return result

def indexesFromSentence(lang, sentence):
    out = []
    for word in sentence.split(' '):
        if word not in lang.word2index:
            continue
        k = lang.word2index[word]
        out.append(k)
    return out




def variableFromSentence(lang, sentence):
    indexes = indexesFromSentence(lang, sentence)
    indexes.append(EOS_token)
    result = Variable(torch.LongTensor(indexes).view(-1, 1))
    if use_cuda:
        return result.cuda()
    return result


def variablesFromPair(pair, input_lang, output_lang):
    input_variable = variableFromSentence(input_lang, pair[0])
    target_variable = variableFromSentence(output_lang, pair[1])
    return (input_variable, target_variable)

teacher_forcing_ratio = 0.5


def train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):
    encoder_hidden = encoder.initHidden()

    encoder_optimizer.zero_grad()
    decoder_optimizer.zero_grad()

    input_length = input_variable.size()[0]
    target_length = target_variable.size()[0]

    encoder_outputs = Variable(torch.zeros(max_length, encoder.hidden_size))
    encoder_outputs = encoder_outputs.cuda() if use_cuda else encoder_outputs



    loss = 0

    for ei in range(input_length):
        encoder_output, encoder_hidden = encoder(
            input_variable[ei], encoder_hidden)
        encoder_outputs[ei] = encoder_output[0][0]

    decoder_input = Variable(torch.LongTensor([[SOS_token]]))
    decoder_input = decoder_input.cuda() if use_cuda else decoder_input


    decoder_hidden = encoder_hidden

    use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False

    if use_teacher_forcing:
        # Teacher forcing: Feed the target as the next input
        for di in range(target_length):
            decoder_output, decoder_hidden, decoder_attention = decoder(
                decoder_input, decoder_hidden, encoder_output, encoder_outputs)
            loss += criterion(decoder_output[0], target_variable[di])
            decoder_input = target_variable[di]  # Teacher forcing

    else:
        # Without teacher forcing: use its own predictions as the next input
        for di in range(target_length):
            decoder_output, decoder_hidden, decoder_attention = decoder(
                decoder_input, decoder_hidden, encoder_output, encoder_outputs)
            topv, topi = decoder_output.data.topk(1)
            ni = topi[0][0]

            decoder_input = Variable(torch.LongTensor([[ni]]))


            loss += criterion(decoder_output[0], target_variable[di])
            if ni == EOS_token:
                break

    loss.backward()

    encoder_optimizer.step()
    decoder_optimizer.step()

    return loss.data[0] / target_length

def seqtoseq_train(n_iters, training_data,print_every=1000, learning_rate=0.01, tfl=False):
    print_loss_total = 0
    hidden_size = 256
    in_lang, out_lang, inwords, outwords = dataclean(training_data)
    metadata = open('app/brain/seqtoseq_meta.pkl', 'wb')
    pk.dump([in_lang, out_lang], metadata)
    if tfl == False:
       encoder = EncoderRNN(inwords, hidden_size)

       decoder = AttnDecoderRNN(hidden_size, outwords, dropout_p=0.1)
    else:
       encoder = torch.load('app/brain/encoder.pt')
       decoder = torch.load('app/brain/decoder.pt')
    if use_cuda:
       encoder = encoder.cuda()
       decoder = decoder.cuda()

    encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)
    decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)
    training_data = [variablesFromPair(random.choice(training_data),in_lang,out_lang)
                      for i in range(n_iters)]
    criterion = nn.NLLLoss()
    if use_cuda:
        criterion = criterion.cuda()

    for iter in range(1, n_iters + 1):
        training_pair = training_data[iter - 1]
        input_variable = training_pair[0]
        target_variable = training_pair[1]

        loss = train(input_variable, target_variable, encoder,
                     decoder, encoder_optimizer, decoder_optimizer, criterion)
        print_loss_total += loss
        accuracy = 100-(loss*100)
        if accuracy < 0:
           accuracy = 0
        if iter%1000 == 0:
           print(accuracy,"%")
    torch.save(encoder, 'app/brain/encoder.pt')
    torch.save(decoder, 'app/brain/decoder.pt')

def evaluate(encoder, decoder, input_lang, output_lang, sentence, max_length=MAX_LENGTH):

    input_variable = variableFromSentence(input_lang, sentence)
    input_length = input_variable.size()[0]
    encoder_hidden = encoder.initHidden()

    encoder_outputs = Variable(torch.zeros(max_length, encoder.hidden_size))
    encoder_outputs = encoder_outputs.cuda() if use_cuda else encoder_outputs



    for ei in range(input_length):
        encoder_output, encoder_hidden = encoder(input_variable[ei],
                                                 encoder_hidden)
        encoder_outputs[ei] = encoder_outputs[ei] + encoder_output[0][0]

    decoder_input = Variable(torch.LongTensor([[SOS_token]]))  # SOS
    decoder_input = decoder_input.cuda() if use_cuda else decoder_input



    decoder_hidden = encoder_hidden

    decoded_words = []
    decoder_attentions = torch.zeros(max_length, max_length)

    for di in range(max_length):
        decoder_output, decoder_hidden, decoder_attention = decoder(
            decoder_input, decoder_hidden, encoder_output, encoder_outputs)
        decoder_attentions[di] = decoder_attention.data
        topv, topi = decoder_output.data.topk(1)
        ni = topi[0][0]
        if ni == EOS_token:
            decoded_words.append('<EOS>')
            break
        else:
            decoded_words.append(output_lang.index2word[ni])

        decoder_input = Variable(torch.LongTensor([[ni]]))
        decoder_input = decoder_input.cuda() if use_cuda else decoder_input


    return decoded_words, decoder_attentions[:di + 1]

def reply_predict(sentence):
    try:
     encoder = torch.load('app/brain/encoder.pt')
     decoder = torch.load('app/brain/decoder.pt')
     with open('app/brain/seqtoseq_meta.pkl','rb') as pickle_file:
          meta = pk.load(pickle_file)
     input_lang = meta[0]
     output_lang = meta[1]
     output_words, attentions = evaluate(encoder, decoder, input_lang, output_lang, sentence)
     output_sentence = ' '.join(output_words)
     return output_sentence.split("<EOS>")[0]
    except(KeyError):
        return random.choice(["sorry i didnt get that","no idea", "i may be malfunctioning", "sorry this is a prototype"])

