import numpy as np
import torch
import matplotlib.pyplot as plt
from logging import Logger
plt.switch_backend('agg')


def adjust_learning_rate(optimizer, epoch, args, log:Logger|None):
    # lr = args.learning_rate * (0.2 ** (epoch // 2))
    if args.lradj == 'type1':
        lr_adjust = {epoch: args.learning_rate * (0.95 ** ((epoch - 1) // 1))}
    elif args.lradj == 'type2':
        lr_adjust = {
            2: 5e-4, 4: 1e-4, 8: 5e-4, 16: 1e-5,
            32: 5e-6, 64: 1e-6
        }
    if epoch in lr_adjust.keys():
        lr = lr_adjust[epoch]
        for param_group in optimizer.param_groups:
            param_group['lr'] = lr
        if log is None:
            print('Updating learning rate to {}'.format(lr))  
        else:
            log.info('Updating learning rate to {}'.format(lr))


class EarlyStopping:
    def __init__(self, patience=7, verbose=False, delta=0, log :Logger|None =None):
        self.patience = patience
        self.verbose = verbose
        self.counter = 0
        self.best_score = None
        self.best_test_score = None
        self.early_stop = False
        self.val_loss_min = np.inf
        self.delta = delta
        self.log = log

    def logging(self, info):
        if self.log is not None:
            self.log.info(info)
        else:
            print(info)

    def __call__(self, val_loss, test_loss, model, cond_model, path):
        is_best = False
        if np.isnan(val_loss) or  np.isnan(test_loss):
            self.early_stop = True
            self.logging('nan in loss')
            return is_best
        score = -val_loss
        test_score = -test_loss

        if self.best_score is None:
            self.best_score = score
            self.best_test_score = test_score
            self.save_checkpoint(val_loss, model, cond_model, path)
        elif score < self.best_score + self.delta:
            self.counter += 1

            self.logging(f'EarlyStopping counter: {self.counter} out of {self.patience}')
            
            if self.counter >= self.patience:
                self.early_stop = True
                self.logging(f"Best test loss: {-self.best_test_score}")
        else:
            self.best_score = score
            self.best_test_score = test_score
            self.save_checkpoint(val_loss, model, cond_model, path)
            self.counter = 0
            is_best = True
        return is_best

    def save_checkpoint(self, val_loss, model, cond_model, path):
        if self.verbose:
            self.logging(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}).  Saving model ...')
        torch.save(model.state_dict(), path + '/' + 'checkpoint.pth')
        torch.save(cond_model.state_dict(), path + '/' + "cond_checkpoint.pth")
        self.val_loss_min = val_loss


class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__


class StandardScaler():
    def __init__(self, mean, std):
        self.mean = mean
        self.std = std

    def transform(self, data):
        return (data - self.mean) / self.std

    def inverse_transform(self, data):
        return (data * self.std) + self.mean


def visual(true, preds=None, name='./pic/test.pdf'):
    """
    Results visualization
    """
    plt.figure()
    plt.plot(true, label='GroundTruth', linewidth=2)
    if preds is not None:
        plt.plot(preds, label='Prediction', linewidth=2)
    plt.legend()
    plt.savefig(name, bbox_inches='tight')
