import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import time
from torch.utils.data import Dataset, DataLoader
import torchvision
import torch.nn.functional as F
import numpy as np
import os

from polymnist_dataset import get_train_test_dataset_upd10_32x32
from mopoe_model import MOPOEPolyRes, MMVAEPolyRes, MVPolyRes, MVTPolyRes

from utils import *

def get_train_test_dataloader_upd10_32x32(batch_size):
    paired_train_dataset, paired_val_dataset, paired_test_dataset = get_train_test_dataset_upd10_32x32()
    train_dataloader = DataLoader(paired_train_dataset, batch_size=batch_size, shuffle=True, num_workers=2)
    val_dataloader = DataLoader(paired_val_dataset, batch_size=batch_size, shuffle=True, num_workers=2)
    test_dataloader = DataLoader(paired_test_dataset, batch_size=batch_size, shuffle=False, num_workers=2)
    return train_dataloader, val_dataloader, test_dataloader

# def get_train_test_dataloader(batch_size):
#     paired_train_dataset, paired_test_dataset = get_train_test_dataset()
#     train_dataloader = DataLoader(paired_train_dataset, batch_size=batch_size, shuffle=True, num_workers=2)
#     test_dataloader = DataLoader(paired_test_dataset, batch_size=batch_size, shuffle=False, num_workers=2)
#     return train_dataloader, test_dataloader

def calc_kl_loss(mu, logvar, cons=1):
    return cons * (-0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())) / mu.shape[0]

def calc_kl_loss_2(mu0, logvar0, mu1, logvar1, cons=1):
    kl2 = -0.5 * (torch.sum(1 - logvar0.exp()/logvar1.exp() - (mu0-mu1).pow(2)/logvar1.exp() + logvar0 - logvar1))
    return cons * kl2 / mu0.shape[0]

def image_loss(x_hat, x, cons=1):
    mse = nn.MSELoss(reduction='sum')
    recon_loss = mse(x_hat, x) / x.shape[0]
    return cons*recon_loss

def total_rec_loss(outs, inputs):
    rec_loss = 0
    for i in range(len(outs)):
        rec_loss += image_loss(outs[i], inputs[i])
    # return (1/len(outs)) * rec_loss
    return 1 * rec_loss

def total_kl_loss(mus, logvars, cons=1):
    kl_losses = 0
    for i in range(len(mus)):
        kl_losses += calc_kl_loss(mus[i], logvars[i])
    return (1/len(mus)) * cons * kl_losses

def mvae_loss(elbo_terms, inputs, kl_cons=1):
    assert len(elbo_terms) == (len(inputs) + 2)
    rec, kl = 0, 0
    # calc individual elbo loss
    for i in range(len(inputs)):
        elbo = elbo_terms[i]
        kl += calc_kl_loss(elbo[0], elbo[1])
        rec += image_loss(elbo[2], inputs[i])

    # calc joint elbo loss
    kl += calc_kl_loss(elbo_terms[len(inputs)][0], elbo_terms[len(inputs)][1])
    for i in range(len(inputs)):
        rec += image_loss(elbo_terms[len(inputs)][2][i], inputs[i])

    # calc kth elbo loss
    kl += calc_kl_loss(elbo_terms[len(inputs)+1][0], elbo_terms[len(inputs)+1][1])
    k_idxs = elbo_terms[len(inputs)+1][2]
    k_outs = elbo_terms[len(inputs)+1][3]
    for i, k_idx in enumerate(k_idxs):
        rec += image_loss(k_outs[i], inputs[k_idx])

    return rec, kl_cons * kl

def mvt_loss(elbo_terms, inputs, kl_cons=1, alpha=0.9):
    assert len(elbo_terms) == (len(inputs) + 1)

    # calc joint elbo loss
    kl_joint = calc_kl_loss(elbo_terms[len(inputs)][0], elbo_terms[len(inputs)][1])
    rec = 0
    for i in range(len(inputs)):
        rec += image_loss(elbo_terms[len(inputs)][2][i], inputs[i])

    kl2 = 0
    # calc individual elbo loss
    for i in range(len(inputs)):
        elbo = elbo_terms[i]
        kl2 += calc_kl_loss_2(elbo_terms[len(inputs)][0], elbo_terms[len(inputs)][1], elbo[0], elbo[1])

    # total_loss
    rec_weight = (len(inputs) - alpha) / len(inputs)
    cvib_weight = alpha / len(inputs) 
    vib_weight = 1 - alpha 
    
    kld_weighted = cvib_weight * kl2 + vib_weight * kl_joint
    return rec_weight * rec, kl_cons * kld_weighted


def train_model(train_loader, model, mix_type, optimizer, all_mods, device, kl_cons):
    losses = {}
    losses['total'], losses['recs'], losses['kls'] = 0, 0, 0
    model.train()
    start_time = time.time()

    for batch_idx, (images, target) in enumerate(train_loader):

        inputs = [images['m' + mod].to(device) for mod in all_mods]

        if mix_type == 'mopoe' or mix_type == 'mmvae':
            outs, mus, logvars = model(inputs)
            rec, kl = total_rec_loss(outs, inputs), total_kl_loss(mus, logvars, kl_cons)
        elif mix_type == 'mvae':
            elbo_terms = model(inputs)
            rec, kl = mvae_loss(elbo_terms, inputs, kl_cons)
        elif mix_type == 'mvt':
            elbo_terms = model(inputs)
            rec, kl = mvt_loss(elbo_terms, inputs, kl_cons)

        losses['recs'], losses['kls'] = losses['recs'] + rec.item(), losses['kls'] + kl.item()
        total_loss = rec + kl
        losses['total'] += total_loss.item()
        
        optimizer.zero_grad()
        total_loss.backward()
        optimizer.step()

    end_time = time.time()
    for loss in losses:
        losses[loss] /= len(train_loader)
    print("TRAINING TIME TAKEN: ", end_time - start_time, flush=True)
    print("Training loss: ", losses, flush=True)
    return list(losses.values())

def evaluate_model(val_loader, model, mix_type, all_mods, device, epoch, vae_type, show=True, kl_cons=1):
    with torch.no_grad():
        losses = {}
        losses['total'], losses['recs'], losses['kls'] = 0, 0, 0
        model.eval()
        start_time = time.time()

        for batch_idx, (images, target) in enumerate(val_loader):

            inputs = [images['m' + mod].to(device) for mod in all_mods]

            if mix_type == 'mopoe' or mix_type == 'mmvae':
                outs, mus, logvars = model(inputs)
                rec, kl = total_rec_loss(outs, inputs), total_kl_loss(mus, logvars, kl_cons)
            elif mix_type == 'mvae':
                elbo_terms = model(inputs)
                rec, kl = mvae_loss(elbo_terms, inputs, kl_cons)
            elif mix_type == 'mvt':
                elbo_terms = model(inputs)
                rec, kl = mvt_loss(elbo_terms, inputs, kl_cons)

            losses['recs'], losses['kls'] = losses['recs'] + rec.item(), losses['kls'] + kl.item()
            total_loss = rec + kl
            losses['total'] += total_loss.item()

            if show and (np.random.uniform() < 0.2):
                # Plot random input and output
                sample_idx = torch.randint(inputs[0].shape[0], size=(1,)).item()
                sample_in = torch.cat([input[sample_idx].permute(1,2,0) for input in inputs], dim=0)
                if mix_type == 'mvae' or mix_type == 'mvt':
                    sample_out = torch.cat([elbo_terms[len(inputs)][2][i][sample_idx].permute(1,2,0) for i in range(len(inputs))], dim=0)
                else:
                    sample_out = torch.cat([out[sample_idx].permute(1,2,0) for out in outs], dim=0)

                concat_tensor = torch.cat([sample_in, sample_out], dim=1)
                # concat_tensor = torchvision.utils.make_grid(concat_tensor)
                plt.imshow(concat_tensor.detach().cpu().numpy())
                plt.title('    Input   Output  ')
                plt.axis("off")
                plt.savefig('./images/mopoe_pupd/' + mix_type + all_mods + "_vae_" + vae_type + str(kl_cons) + "_" + str(epoch) + '__' + str(batch_idx) + ".png")
            
        end_time = time.time()
        for loss in losses:
            losses[loss] /= len(val_loader)
        print("VALIDATION TIME TAKEN: ", end_time - start_time, flush=True)
        # print("fids: ", fids, flush=True)
        print("Validation loss: ", losses, flush=True)
        return list(losses.values())   


def run(epochs, batch_size, lr, size_z, beta, unq_name, vae_type, mix_type, all_mods, cuda_num):
    kl_cons = beta
    print('vars: ', epochs, batch_size, lr, size_z, kl_cons, unq_name, vae_type, mix_type)
    train_losses, val_losses = [], []
    
    for p in ['./models/mopoe_pupd/', './plots/mopoe_pupd/', './images/mopoe_pupd/']:
        if not os.path.exists(p):
            os.makedirs(p)

    cuda = torch.cuda.is_available()
    print("GPU Available: ", cuda, flush=True)
    device = torch.device("cuda:"+str(cuda_num))
    print("device: ", torch.cuda.get_device_properties(device), flush=True)

    if vae_type == 'res':
        enc_channel_list = [(64,64,64,2), (64,128,128,2), (128,256,256,2)]
        dec_channel_list = [(256,128,128,2), (128,128,64,2), (64,64,64,2)]
        size_in = 32
        img_ch = 3
        if mix_type == 'mopoe':
            mix_vae = MOPOEPolyRes(len(all_mods), enc_channel_list, dec_channel_list, size_z, size_in, img_ch)
        elif mix_type == 'mmvae':
            mix_vae = MMVAEPolyRes(len(all_mods), enc_channel_list, dec_channel_list, size_z, size_in, img_ch)
        elif mix_type == 'mvae':
            mix_vae = MVPolyRes(len(all_mods), enc_channel_list, dec_channel_list, size_z, size_in, img_ch)
        elif mix_type == 'mvt':
            mix_vae = MVTPolyRes(len(all_mods), enc_channel_list, dec_channel_list, size_z, size_in, img_ch)

    # else:
    #     if mix_type == 'mopoe':
    #         mix_vae = MOPOEPoly(device, [ConvPoly]*len(all_mods), size_z)
    #     else:
    #         raise Exception('Not Implemented')
    optimizer = torch.optim.Adam(mix_vae.parameters(), lr=lr)
    mix_vae = mix_vae.to(device)
    scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=5)

    # print("test", flush=True)
    # mix_vae([torch.randn(100,3,28,28).to(device)]*10)
    # print("passed test", flush=True)
    print("Mods: ", all_mods, flush=True)
    
    if vae_type == 'res':
        train_dataloader, test_dataloader, _ = get_train_test_dataloader_upd10_32x32(batch_size)
    # else:
    #     train_dataloader, test_dataloader, _ = get_train_test_dataloader_upd10(batch_size)
    
    for epoch in range(epochs):
        print("Epoch: "+str(epoch + 1), flush=True)

        training_loss = train_model(train_dataloader, mix_vae, mix_type, optimizer, all_mods, device, kl_cons)
        validation_loss = evaluate_model(test_dataloader, mix_vae, mix_type, all_mods, device, epoch, vae_type, True, kl_cons)
        print(' ', flush=True)

        train_losses.append(training_loss)
        val_losses.append(validation_loss)
        scheduler.step(validation_loss[0])

        if epoch == 0:
            prev_loss = validation_loss[0]
        if epoch > 0 and (validation_loss[0] < prev_loss):
            torch.save({
            'epoch': epoch,
            'model_state_dict': mix_vae.state_dict(),
            'optimizer_state_dict': optimizer.state_dict(),
            'train_loss': training_loss[0],
            'val_loss': validation_loss[0],
            'beta': kl_cons,
            'size_z': size_z,
            }, "./models/mopoe_pupd/" + mix_type + "_vae_" + vae_type + "_beta_" + str(kl_cons) + "__" + str(size_z) + all_mods + '_' + unq_name)
            print('Model saved', flush=True)
            prev_loss = validation_loss[0]

    train_losses, val_losses = np.array(train_losses), np.array(val_losses)
    save_loss_plot(train_losses, val_losses, \
        ['Total loss', 'Recon', 'KL'],
        ['Epoch']*3, 
        ['Total loss', 'Recon', 'KL'], './plots/mopoe_pupd/' + mix_type + "_vae_" + vae_type + "_beta_" + str(kl_cons) + "__" + str(size_z) + all_mods + '_' + unq_name)  
    

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()

    parser.add_argument('--size-z', type=int, default=64,
                        help='size of z [default: 64]')
    parser.add_argument('--all-mods', type=str, default='0123456789',
                        help='all mods [default: "0123456789"]')
    parser.add_argument('--batch-size', type=int, default=512,
                        help='batch size for training [default: 512]')
    parser.add_argument('--epochs', type=int, default=200,
                        help='number of epochs to train [default: 200]')
    parser.add_argument('--cuda', type=int, default=3,
                        help='number of cuda_gpu [default: 3]')
    parser.add_argument('--beta', type=float, default=0.5,
                        help='beta value for kl loss [default: 0.5]')
    parser.add_argument('--lr', type=float, default=0.001,
                        help='learning rate [default: 0.001]')
    parser.add_argument('--unq-name', type=str, default='',
                        help='identifier name for saving [default: ""]')
    parser.add_argument('--mix-type', type=str, default='mopoe',
                        help='mixture type [default: "mopoe"]')
    parser.add_argument('--vae-type', type=str, default='res',
                        help='vae type [default: "res"]')
    
    args = parser.parse_args()

    run(args.epochs, args.batch_size, args.lr, args.size_z, args.beta, args.unq_name, args.vae_type, args.mix_type, args.all_mods, args.cuda)