import copy
import datetime
import glob
import os
import time
import cv2
import matplotlib.pyplot as plt
import torchvision.transforms.functional as TF
import torch
import numpy as np
from sklearn.metrics import confusion_matrix
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from torchvision import transforms
from tqdm.notebook import tqdm
from source.losses import *
from source.models import *
from source.utils import *
import pytorch_lightning as pl
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint
from source.losses import *
import pandas as pd

class DownSampleConv(nn.Module):

    def __init__(self, in_channels, out_channels, kernel=4, strides=2, padding=1, activation=True, batchnorm=True):
        """
        Paper details:
        - C64-C128-C256-C512-C512-C512-C512-C512
        - All convolutions are 4×4 spatial filters applied with stride 2
        - Convolutions in the encoder downsample by a factor of 2
        """
        super().__init__()
        self.activation = activation
        self.batchnorm = batchnorm

        self.conv = nn.Conv2d(in_channels, out_channels, kernel, strides, padding)

        if batchnorm:
            self.bn = nn.BatchNorm2d(out_channels)

        if activation:
            self.act = nn.LeakyReLU(0.2)

    def forward(self, x):
        x = self.conv(x)
        if self.batchnorm:
            x = self.bn(x)
        if self.activation:
            x = self.act(x)
        return x

class PatchGAN(nn.Module):

    def __init__(self, input_channels):
        super().__init__()
        self.d1 = DownSampleConv(input_channels, 64, batchnorm=False)
        self.d2 = DownSampleConv(64, 128)
        self.d3 = DownSampleConv(128, 256)
        self.d4 = DownSampleConv(256, 512)
        self.final = nn.Conv2d(512, 1, kernel_size=1)

    def forward(self, x, y):
        x = torch.cat([x, y], axis=1)
        x0 = self.d1(x)
        x1 = self.d2(x0)
        x2 = self.d3(x1)
        x3 = self.d4(x2)
        xn = self.final(x3)
        return xn


# collapse-hide
# https://stackoverflow.com/questions/49433936/how-to-initialize-weights-in-pytorch

def _weights_init(m):
    if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):
        torch.nn.init.normal_(m.weight, 0.0, 0.02)
    if isinstance(m, nn.BatchNorm2d):
        torch.nn.init.normal_(m.weight, 0.0, 0.02)
        torch.nn.init.constant_(m.bias, 0)


def display_progress(cond, fake, real, figsize=(10, 5)):
    cond = cond.detach().cpu().permute(1, 2, 0)
    fake = fake.detach().cpu().permute(1, 2, 0)
    real = real.detach().cpu().permute(1, 2, 0)

    fig, ax = plt.subplots(1, 3, figsize=figsize)
    ax[0].imshow(cond)
    ax[1].imshow(real)
    ax[2].imshow(fake.sigmoid())
    plt.show()


class Pix2Pix(pl.LightningModule):

    def __init__(self, in_channels, out_channels, learning_rate=0.0002, lambda_recon=200, display_step=25, pruning=False):

        super().__init__()
        self.save_hyperparameters()

        self.display_step = display_step
        if pruning:
            self.gen = UNet_Pruning(n_class=out_channels)
        else:
            self.gen = UNet(n_class=out_channels)

        self.patch_gan = PatchGAN(in_channels + out_channels)

        # intializing weights
        self.gen = self.gen.apply(_weights_init)
        self.patch_gan = self.patch_gan.apply(_weights_init)

        # self.adversarial_criterion = nn.BCEWithLogitsLoss()
        self.adversarial_criterion = DiceCE(bce_weight=0.5)
        self.recon_criterion = nn.L1Loss()

    def _gen_step(self, real_images, conditioned_images):
        # Pix2Pix has adversarial and a reconstruction loss
        # First calculate the adversarial loss
        fake_images = self.gen(conditioned_images)
        disc_logits = self.patch_gan(fake_images, conditioned_images)
        adversarial_loss = self.adversarial_criterion(disc_logits, torch.ones_like(disc_logits))

        # calculate reconstruction loss
        recon_loss = self.recon_criterion(fake_images, real_images)
        lambda_recon = self.hparams.lambda_recon

        return adversarial_loss + lambda_recon * recon_loss

    def _disc_step(self, real_images, conditioned_images):
        fake_images = self.gen(conditioned_images).detach()
        fake_logits = self.patch_gan(fake_images, conditioned_images)

        real_logits = self.patch_gan(real_images, conditioned_images)

        fake_loss = self.adversarial_criterion(fake_logits, torch.zeros_like(fake_logits))
        real_loss = self.adversarial_criterion(real_logits, torch.ones_like(real_logits))
        return (real_loss + fake_loss) / 2

    def configure_optimizers(self):
        lr = self.hparams.learning_rate
        gen_opt = torch.optim.Adam(self.gen.parameters(), lr=lr)
        disc_opt = torch.optim.Adam(self.patch_gan.parameters(), lr=lr)
        return disc_opt, gen_opt

    def training_step(self, batch, batch_idx, optimizer_idx):
        condition, real = batch

        loss = None
        if optimizer_idx == 0:
            loss = self._disc_step(real, condition)
            self.log('PatchGAN Loss', loss)
        elif optimizer_idx == 1:
            loss = self._gen_step(real, condition)
            self.log('Generator Loss', loss)

        if self.current_epoch % self.display_step == 0 and batch_idx == 0 and optimizer_idx == 1:
            fake = self.gen(condition).detach()
            display_progress(condition[0], fake[0], real[0])
        return loss


class TongueSegDataset(torch.utils.data.Dataset):
    def __init__(self, path_sampleDir, path_labelDir, transform_sample=None, transform_label=None, transform_both=None):
        super().__init__()

        self.transform_sample = transform_sample
        self.paths_sample = glob.glob(os.path.join(path_sampleDir, '*'))

        self.paths_label = []
        for path_sample in self.paths_sample:
            self.paths_label.append(os.path.join(path_labelDir, os.path.basename(path_sample)))
        self.transform_label = transform_label

        self.transform_both = transform_both

    def __getitem__(self, index):

        # Load sample
        path_sample = self.paths_sample[index]
        sample = torch.from_numpy(cv2.imread(path_sample, cv2.IMREAD_COLOR)) / 255.0
        sample = sample.permute(2, 0, 1).float()
        if self.transform_sample:
            sample = self.transform_sample(sample)

        # Load label
        path_label = self.paths_label[index]
        label = torch.from_numpy(cv2.imread(path_label, cv2.IMREAD_COLOR))
        label[label <= 128] = 0.0
        label[label > 128] = 1.0
        label = label.permute(2, 0, 1).float()
        if self.transform_label:
            label = self.transform_label(label)

        if self.transform_both:
            for tf, p in self.transform_both:
                if random.random() < p:
                    sample = tf(sample)
                    label = tf(label)

        # label_pos = label[0, :, :]
        # label_neg = torch.ones(label_pos.shape) - label[0, :, :]
        # label_pos = label_pos.unsqueeze(0)
        # label_neg = label_neg.unsqueeze(0)
        # label = torch.cat([label_pos, label_neg], axis=0)
        return sample, label

    def __len__(self):
        return len(self.paths_sample)

def train():
    # Configs
    path_outputDir = os.path.join("..\output", datetime.datetime.now().strftime('%m%d-%H%M%S'))
    os.makedirs(path_outputDir)

    # load data train
    path_trainSample = os.path.join("..\input", "train", "sample")
    path_trainLabel = os.path.join("..\input", "train", "label")
    path_testSample = os.path.join("..\input", "test_extra", "cropped", "sample")
    path_testLabel = os.path.join("..\input", "test_extra", "cropped", "label")

    # Params
    fix_rand(2021)
    train_ratio = 2 / 3
    num_epochs = 300
    num_epochsEarlyStop = 30
    display_step = 5
    lambda_recon = 100
    batch_size = 16
    lr = 0.0001
    target_size = 256
    transform_sample = transforms.Compose([transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)])
    transform_label = transforms.Compose([])
    transform_both = [(TF.hflip, 0.5)]
    dataset = TongueSegDataset(path_trainSample, path_trainLabel, transform_sample=transform_sample,
                               transform_label=transform_label, transform_both=transform_both)

    train_dataset, val_dataset = torch.utils.data.random_split(dataset,
                                      [int(len(dataset) * train_ratio), len(dataset) - int(len(dataset) * train_ratio)])
    data_loader_train = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)
    data_loader_val = DataLoader(val_dataset, batch_size=batch_size, shuffle=True, num_workers=0)
    print("train:", len(train_dataset), "  validation:", len(val_dataset))

    pix2pix = Pix2Pix(3, 3, pruning=True, learning_rate=lr, lambda_recon=lambda_recon, display_step=display_step)
    early_stop_callback = EarlyStopping(monitor="PatchGAN Loss", patience=num_epochsEarlyStop)
    trainer = pl.Trainer(max_epochs=num_epochs, gpus=1, callbacks=[early_stop_callback], log_every_n_steps=16,)
    trainer.fit(pix2pix, train_dataloader=data_loader_train, val_dataloaders=data_loader_val)
    torch.save(pix2pix.state_dict(), path_outputDir + r"/bestModel.pth")

def eval():
    fix_rand(2021)
    path_outputDir = os.path.join("..\output", datetime.datetime.now().strftime('%m%d-%H%M%S'))
    os.makedirs(path_outputDir)
    path_testSample = os.path.join("..\input", "test_extra", "cropped", "sample")
    path_testLabel = os.path.join("..\input", "test_extra", "cropped", "label")
    dataset_test = TongueSegDataset(path_testSample, path_testLabel)
    data_loader_test = DataLoader(dataset_test, batch_size=1, shuffle=False)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    path_model = r"D:\Noguchi\Solution\TongueSegmentation\result\CompareModels\Pix2Pix_Pruning\bestModel.pth"
    model = Pix2Pix(3, 3, pruning=True)
    # パラメータカウント
    params = 0
    for p in model.parameters():
        params += p.numel()
    print("params: ", params)
    model.load_state_dict(torch.load(path_model))
    model = model.gen
    model.to(device)



    # 推論時間計測
    since = time.perf_counter()
    for repeated in range(10):
        for i, data in enumerate(data_loader_test, 0):
            inputs = data[0].to(device)
            labels = data[1].to(device)
            outputs = model(inputs).sigmoid()
            pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0]
            ret, img_pred = cv2.threshold((pred * 255).astype(np.uint8), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    time_elapsed = (time.perf_counter() - since) / 10.0
    print("time: ", time_elapsed)

    with open(path_outputDir + r'/test_time&params.csv', 'x', encoding='utf-8') as f:
        f.write("time," + str(time_elapsed) + "\n")
        f.write("params," + str(params) + "\n")

    # Evaluation
    shouldSave = True
    shouldShow = False
    ious = []
    df = pd.DataFrame()
    for i, data in tqdm(enumerate(data_loader_test, 0)):
        name = os.path.splitext(os.path.basename(glob.glob(path_testSample + "/*")[i]))[0]

        inputs = data[0].to(device)
        labels = data[1].to(device)
        outputs = model(inputs).sigmoid()

        pred = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, :]
        pred = cv2.cvtColor(pred, cv2.COLOR_BGR2GRAY)
        true = labels.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0]

        img_pred = (pred * 255).astype(np.uint8)
        # otsu
        ret, img_pred = cv2.threshold(img_pred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

        y_pred = (img_pred / 255).flatten()
        y_true = true.flatten()
        tn, fp, fn, tp = confusion_matrix(y_pred, y_true).ravel()

        iou_tp = tp / (tp + fp + fn)

        ious.append(iou_tp)

        r = pd.DataFrame([name, tn, fp, fn, tp, iou_tp]).T
        df = pd.concat([df, r], axis=0)

        if shouldSave and (i >= 175 or i ==153 or i==150):
            num_output = outputs.permute(0, 2, 3, 1).to('cpu').detach().numpy()[0, :, :, 0]
            plt.axis("off")
            plt.imshow(img_pred)
            cv2.imwrite(path_outputDir + r"/" + str(i + 1) + ".png", img_pred)

        if os.path.exists(path_outputDir + r'/Log_detail.csv'):
            with open(path_outputDir + r'/Log_detail.csv', 'a', encoding='utf-8') as f:
                f.write(name + ", " + str(iou_tp) + "\n")
        else:
            with open(path_outputDir + r'/Log_detail.csv', 'x', encoding='utf-8') as f:
                f.write(name + ", " + str(iou_tp) + "\n")

    df.columns = ["name", "tn", "fp", "fn", "tp", "iou_tp"]
    mean = pd.DataFrame(df.mean(axis=0)).T
    df = pd.concat([df, mean])
    df.to_csv(path_outputDir + r'/Log_detail.csv', index=False)
    #
    print("全体平均:", np.array(ious).mean())
    if os.path.exists(path_outputDir + r'/Log.txt'):
        with open(path_outputDir + r'/Log.txt', 'w', encoding='utf-8') as f:
            s = f.write("全体平均:" + str(np.array(ious).mean()))
    else:
        with open(path_outputDir + r'/Log.txt', 'x', encoding='utf-8') as f:
            s = f.write("全体平均:" + str(np.array(ious).mean()))

# TODO early stoppingした時や，いい感じのlossでモデルを随時保存する
# check point call back　で実装できるが，データ構造が嫌いなので，スクラッチで実装したい．
# あと，間違えて出力がカラーになるように構築してしまったが，2 or 1でよい
# train()
eval()
