# coding=utf-8

import os
import shutil

import torch


def save_checkpoint(state, is_best, model_dir, filename='checkpoint.pth.tar'):
    model_fname = os.path.join(model_dir, filename)
    torch.save(state, model_fname)
    if is_best:
        shutil.copyfile(model_fname,
                        os.path.join(model_dir, 'model_best.pth.tar'))

def save_checkpoint_main_client(state, is_best, model_dir):
    # model_fname = os.path.join(model_dir, filename)
    # torch.save(state, model_fname)
    if is_best:
        print("Saving best client")
        torch.save(state,os.path.join(model_dir, 'main_client_best.pth.tar'))
        # shutil.copyfile(model_fname,
        #                 os.path.join(model_dir, 'model_best.pth.tar'))

def save_checkpoint_proxy_clients(state, is_best, model_dir):
    # model_fname = os.path.join(model_dir, filename)
    # torch.save(state, model_fname)
    if is_best:
        print("Saving best proxy")
        torch.save(state,os.path.join(model_dir, 'proxy_clients_best.pth.tar'))
        # shutil.copyfile(model_fname,
        #                 os.path.join(model_dir, 'model_best.pth.tar'))

def save_checkpoint_client(state, is_best, model_dir):
    # model_fname = os.path.join(model_dir, filename)
    # torch.save(state, model_fname)
    if is_best:
        print("Saving best client")
        torch.save(state,os.path.join(model_dir, 'client_best.pth.tar'))
        # shutil.copyfile(model_fname,
        #                 os.path.join(model_dir, 'model_best.pth.tar'))

def save_checkpoint_server(state, is_best, model_dir):
    # model_fname = os.path.join(model_dir, filename)
    # torch.save(state, model_fname)
    if is_best:
        print("Saving best proxy")
        torch.save(state,os.path.join(model_dir, 'server_best.pth.tar'))
        # shutil.copyfile(model_fname,
        #                 os.path.join(model_dir, 'model_best.pth.tar'))
class AverageMeter(object):
    """Computes and stores the average and current value"""
    def __init__(self, name, fmt=':f'):
        self.name = name
        self.fmt = fmt
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

    def __str__(self):
        fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
        return fmtstr.format(**self.__dict__)


class ProgressMeter(object):
    def __init__(self, num_batches, *meters, prefix=""):
        self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
        self.meters = meters
        self.prefix = prefix

    def print(self, batch):
        entries = [self.prefix + self.batch_fmtstr.format(batch)]
        entries += [str(meter) for meter in self.meters]
        print('\t'.join(entries))

    def _get_batch_fmtstr(self, num_batches):
        num_digits = len(str(num_batches // 1))
        fmt = '{:' + str(num_digits) + 'd}'
        return '[' + fmt + '/' + fmt.format(num_batches) + ']'


def accuracy(output, target, topk=(1,)):
    """
    Computes the accuracy over the k top predictions for the specified values
    of k
    """
    with torch.no_grad():
        maxk = max(topk)
        batch_size = target.size(0)

        _, pred = output.topk(maxk, 1, True, True)
        pred = pred.t()
        correct = pred.eq(target.view(1, -1).expand_as(pred))

        res = []
        for k in topk:
            correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
            res.append(correct_k.mul_(100.0 / batch_size))
        return res


def get_the_number_of_params(model, is_trainable=False):
    """get the number of the model"""
    if is_trainable:
        return sum(p.numel() for p in model.parameters() if p.requires_grad)
    return sum(p.numel() for p in model.parameters())
