import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable


def ard_loss(model,
              x_natural,
              y,
              teacher_outputs,
              optimizer,
              step_size=0.007,
              epsilon=0.031,
              perturb_steps=10,
              temp=30.0,
              distance='l_inf'):
    kl = nn.KLDivLoss().cuda()
    model.eval()
    batch_size = len(x_natural)
    # generate adversarial example
    x_adv = x_natural.detach() + 0.001 * torch.randn(x_natural.shape).cuda().detach()
    if distance == 'l_inf':
        for _ in range(perturb_steps):
            x_adv.requires_grad_()
            with torch.enable_grad():
                loss_ce = F.cross_entropy(model(x_adv), y)
            grad = torch.autograd.grad(loss_ce, [x_adv])[0]
            x_adv = x_adv.detach() + step_size * torch.sign(grad.detach())
            x_adv = torch.min(torch.max(x_adv, x_natural - epsilon), x_natural + epsilon)
            x_adv = torch.clamp(x_adv, 0.0, 1.0)
    else:
        x_adv = torch.clamp(x_adv, 0.0, 1.0)

    model.train()

    x_adv = Variable(torch.clamp(x_adv, 0.0, 1.0), requires_grad=False)
    # zero gradient
    optimizer.zero_grad()

    logits_adv = model(x_adv)

    loss_robust = temp * temp * kl(F.log_softmax(logits_adv/temp, dim=1),F.softmax(teacher_outputs/temp, dim=1))

    return logits_adv, loss_robust