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=True
SEED=50
WIDTH=8
print(SEED)
#method=['our_fullgrad']#,
method=['Our_GBP']
#method=['our_method_minus_mean']
#method=['our+']
#method=['Saliency','GradCAM','FullGrad']
#method=['InputXGradient','DeepLIFT','IntegratedGradients']
#method=['IntegratedGradients']#,'random'
#method=['FullGrad']
#method=['GradCAM']
#method = ['GIG','GradCAM','FullGrad','our_method_minus_mean' ]
#method=['DeepLIFT','Saliency','CAMERAS','IntegratedGradients','our_method']


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=SEED, 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)
        np.random.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 obtain_images_bbox():
    targets = np.load('targets.npy')
    images=np.load('images.npy')
    bboxes=np.load('bboxes.npy')
    images,targets,bboxes=torch.Tensor(images),torch.Tensor(targets),torch.Tensor(bboxes)
    num=5
    images=torch.split(images,num)
    targets=torch.split(targets,num)
    bboxes=torch.split(bboxes,num)
    return images,targets,bboxes

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()
    import ADGT
    adgt = ADGT.ADGT(use_cuda=True, name='ImageNet')
    cudnn.benchmark = True
    images, targets, bboxes=obtain_images_bbox()
    n_max=len(images)-1
    index=np.arange(n_max)
    np.random.shuffle(index)
    num=0
    result={'model':RESNET}
    for m in method:
        result[m]=0
    print(result)
    edge_mask=torch.ones(1,1,224,224).cuda()
    edge_mask[:,:,0:WIDTH,:]=0
    edge_mask[:, :, -WIDTH:, :] = 0
    edge_mask[:, :, :,0:WIDTH] = 0
    edge_mask[:, :, :, -WIDTH:] = 0
    for i in range(100):
        x,t,b=images[index[i]],targets[index[i]],bboxes[index[i]]
        x,t,b=x.clone().cuda(),t.cuda(),b.clone().cuda()
        #print(x.size(),b.size())
        num+=x.size(0)
        #print(t.size())
        for m in method:
            heatmaps = adgt.pure_explain(x, model, m,top1=t.long())
            heatmaps=F.relu(heatmaps).detach()
            heatmaps=heatmaps*edge_mask
            proportion=torch.sum(heatmaps*b)/(torch.sum(heatmaps)+1e-8)
            result[m]+=(proportion*x.size(0)).item()
        if i %10==0:
            print(num,result)

    print(num)
    print(result)

if __name__ == '__main__':
    main()