import argparse
import os
import random
import shutil
import time
import warnings

import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
from torch.utils.tensorboard import SummaryWriter
from attribution_methods.our.model import resnet,vgg
from attribution_methods.our import networks as nw
import numpy as np
import torch.nn.functional as F
RESNET=False
MOST_SALIENCY=True
print(RESNET,MOST_SALIENCY)
#THIRD=True
DATASET='test'#'train'#
method=['Our_GBP']#,
#method=['our_method_minus_mean','Saliency','GradCAM']
#method=['IntegratedGradients','FullGrad','DeepLIFT']#
#method=['GIG','our_method','CAMERAS']#,'random'
#method=['Saliency']
#method=['our_method_minus_mean',]
#method=['our_method','GIG']
#method=['IntegratedGradients','DeepLIFT']

percetile=['10','30','50','70','90','100']
#percetile=['100']
torch.set_num_threads(4)

os.environ["CUDA_VISIBLE_DEVICES"] = "5"
model_names = sorted(name for name in models.__dict__
    if name.islower() and not name.startswith("__")
    and callable(models.__dict__[name]))

parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('--data', metavar='DIR',default='/data_SSD2/zgh/workspace/data/ImageNet',
                    help='path to dataset')
parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50',
                    choices=model_names,
                    help='model architecture: ' +
                        ' | '.join(model_names) +
                        ' (default: resnet18)')
parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',
                    help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=90, type=int, metavar='N',
                    help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
                    help='manual epoch number (useful on restarts)')
parser.add_argument('-b', '--batch-size', default=8, type=int,
                    metavar='N',
                    help='mini-batch size (default: 256), this is the total '
                         'batch size of all GPUs on the current node when '
                         'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,
                    metavar='LR', help='initial learning rate', dest='lr')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
                    help='momentum')
parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float,
                    metavar='W', help='weight decay (default: 1e-4)',
                    dest='weight_decay')
parser.add_argument('-p', '--print-freq', default=10, type=int,
                    metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
                    help='path to latest checkpoint (default: none)')
parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',
                    help='evaluate model on validation set')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
                    help='use pre-trained model')
parser.add_argument('--world-size', default=-1, type=int,
                    help='number of nodes for distributed training')
parser.add_argument('--rank', default=-1, type=int,
                    help='node rank for distributed training')
parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,
                    help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='nccl', type=str,
                    help='distributed backend')
parser.add_argument('--seed', default=None, type=int,
                    help='seed for initializing training. ')
parser.add_argument('--gpu', default=None, type=int,
                    help='GPU id to use.')
parser.add_argument('--multiprocessing-distributed', action='store_true',
                    help='Use multi-processing distributed training to launch '
                         'N processes per node, which has N GPUs. This is the '
                         'fastest way to use PyTorch for either single node or '
                         'multi node data parallel training')

def main():
    args = parser.parse_args()

    if args.seed is not None:
        random.seed(args.seed)
        torch.manual_seed(args.seed)
        cudnn.deterministic = True
        warnings.warn('You have chosen to seed training. '
                      'This will turn on the CUDNN deterministic setting, '
                      'which can slow down your training considerably! '
                      'You may see unexpected behavior when restarting '
                      'from checkpoints.')

    if args.gpu is not None:
        warnings.warn('You have chosen a specific GPU. This will completely '
                      'disable data parallelism.')

    if args.dist_url == "env://" and args.world_size == -1:
        args.world_size = int(os.environ["WORLD_SIZE"])

    args.distributed = args.world_size > 1 or args.multiprocessing_distributed

    ngpus_per_node = torch.cuda.device_count()
    if args.multiprocessing_distributed:
        # Since we have ngpus_per_node processes per node, the total world_size
        # needs to be adjusted accordingly
        args.world_size = ngpus_per_node * args.world_size
        # Use torch.multiprocessing.spawn to launch distributed processes: the
        # main_worker process function
        mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))
    else:
        # Simply call main_worker function
        main_worker(args.gpu, ngpus_per_node, args)


def main_worker(gpu, ngpus_per_node, args):
    global best_acc1
    args.gpu = gpu

    if args.gpu is not None:
        print("Use GPU: {} for training".format(args.gpu))

    if args.distributed:
        if args.dist_url == "env://" and args.rank == -1:
            args.rank = int(os.environ["RANK"])
        if args.multiprocessing_distributed:
            # For multiprocessing distributed training, rank needs to be the
            # global rank among all the processes
            args.rank = args.rank * ngpus_per_node + gpu
        dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
                                world_size=args.world_size, rank=args.rank)
    # create model

    if RESNET:
        model=resnet.resnet50(pretrained=True)
    else:
        model=vgg.vgg16_bn(pretrained=True)
    if not torch.cuda.is_available():
        print('using CPU, this will be slow')
    else:
        #torch.cuda.set_device(args.gpu)
        model = model.cuda()
        model.eval()

    cudnn.benchmark = True

    traindir = os.path.join(args.data, 'train')
    valdir = os.path.join(args.data, 'val')
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225])
    '''
    train_dataset = datasets.ImageFolder(
        traindir,
        transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            normalize,
        ]))
    if args.distributed:
        train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
    else:
        train_sampler = None
    train_loader = torch.utils.data.DataLoader(
        train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),
        num_workers=args.workers, pin_memory=True, sampler=train_sampler)
    '''
    val_loader = torch.utils.data.DataLoader(
        datasets.ImageFolder(valdir, transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            normalize,
        ])),
        batch_size=args.batch_size, shuffle=True,
        num_workers=args.workers, pin_memory=True)

    results={}
    results['num']=0
    for m in method:
        results[m]={}
        for p in percetile:
            results[m][p]=[0,0]
    model.eval()
    K=5
    import ADGT
    adgt = ADGT.ADGT(use_cuda=True, name='ImageNet')
    if DATASET=='train':
        loader=None
    else:
        loader=val_loader
    if True:
        end = time.time()
        for i, (images, target) in enumerate(loader):
            images, target = images.cuda(), target.cuda()
            results['num']+=images.size(0)
            with torch.no_grad():
                base=model(images)
                base=F.softmax(base,1)
                top1=torch.argmax(base,1)
            for m in method:
                heatmaps=adgt.pure_explain(images,model,m).detach()
                #print(heatmaps.size())
                for p in percetile:
                    if MOST_SALIENCY:
                        maskimg = perturb_most(images, heatmaps, int(p))
                    else:
                        maskimg=perturb(images,heatmaps,int(p),m)
                    with torch.no_grad():
                        out=model(maskimg)
                        out=F.softmax(out,1)
                        iii=torch.arange(images.size(0))
                        results[m][p][0]+=torch.sum(torch.abs(out[iii,top1]-base[iii,top1])).item()
                        top_out = torch.argmax(out, 1)
                        results[m][p][1]+=torch.sum((top_out==target).float()).item()
            if i%10==0:
                print(results)
    print(results)

def perturb_most(images,heatmaps,p):
    p=100-p
    temp=heatmaps.cpu().numpy()
    pvalue=[]
    for i in range(heatmaps.size(0)):
        t=np.percentile(temp[i],p)
        pvalue.append(t)
    pvalue=torch.Tensor(np.array(pvalue)).to(images).view(-1,1,1,1)
    mask=torch.lt(heatmaps.to(images),pvalue).float()
    #print(torch.sum(mask).item()/torch.sum(torch.ones_like(mask)).item(),p)
    return images*mask

def perturb(images,heatmaps,p,method=None):
    if method not in ['GIG','DeepLIFT','IntegratedGradients']:
        temp = heatmaps.cpu().numpy()
    else:
        temp=np.abs(heatmaps.cpu().numpy())

    pvalue=[]
    for i in range(heatmaps.size(0)):
        t=np.percentile(temp[i],p)
        pvalue.append(t)
    pvalue=torch.Tensor(np.array(pvalue)).cuda().view(-1,1,1,1)

    if method not in ['GIG','DeepLIFT','IntegratedGradients']:
        mask = torch.gt(heatmaps, pvalue).float()
    else:
        mask = torch.gt(torch.abs(heatmaps), pvalue).float()
    return images*mask

def FGSM(img,model,criterion,K):
    eps = 8

    inp=img.requires_grad_(True)

    pred = model(inp)
    _, topklabel = torch.topk(pred, K)
    rand_num=(torch.rand(img.size(0))*(K-1)).long()+1
    iii = torch.arange(img.size(0))
    target = topklabel[iii, rand_num]
    loss = criterion(pred, target)

    # compute gradients
    loss.backward()

    # this is it, this is the method
    inp.data = inp.data + ((eps / 255.0/0.225) * torch.sign(inp.grad.data))
    inp.grad.data.zero_()
    return inp

def Iterative(img,model,criterion,K):
    eps = 8
    alpha=10

    inp=img.requires_grad_(True)
    pred = model(inp)
    _, topklabel = torch.topk(pred, K)
    rand_num = (torch.rand(img.size(0)) * (K - 1)).long() + 1
    iii = torch.arange(img.size(0))
    target = topklabel[iii, rand_num]
    loss = criterion(pred, target)

    # compute gradients
    loss.backward()
    perturbation=torch.clamp((alpha / 255.0/0.225) * torch.sign(inp.grad.data), min=-eps/255.0/0.225, max=eps/255.0/0.225)
    inp.grad.data.zero_()
    for i in range(10):
        pred = model(inp+perturbation)
        _, topklabel = torch.topk(pred, K)
        loss = criterion(pred, target)

        # compute gradients
        loss.backward()
        perturbation=torch.clamp(perturbation+(alpha / 255.0/0.225) * torch.sign(inp.grad.data), min=-eps/255.0/0.225, max=eps/255.0/0.225)
        inp.grad.data.zero_()
    return inp+perturbation

if __name__ == '__main__':
    main()