import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
import math
import pdb


class ArcfaceLinear(nn.Module):
    r"""Implement of large margin arc distance: :
        Args:
            in_features: size of each input sample
            out_features: size of each output sample
            s: norm of input feature
            m: margin

            cos(theta + m)
        """
    def __init__(self, in_features, out_features, m=0.50, easy_margin=False):
        super(ArcfaceLinear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.m = m
        self.weight = Parameter(torch.FloatTensor(out_features, in_features))
        nn.init.xavier_uniform_(self.weight)

        self.easy_margin = easy_margin
        self.cos_m = math.cos(m)
        self.sin_m = math.sin(m)
        self.th = math.cos(math.pi - m)
        self.mm = math.sin(math.pi - m) * m

    def forward(self, input):
        # --------------------------- cos(theta) & phi(theta) ---------------------------
        cosine = F.linear(F.normalize(input), F.normalize(self.weight))
        sine = torch.sqrt(1.0 - torch.pow(cosine, 2))
        phi = cosine * self.cos_m - sine * self.sin_m
        # this condition controls the theta+m should in range [0, pi]
        #      0<=theta+m<=pi
        #     -m<=theta<=pi-m
        if self.easy_margin:
            phi = torch.where(cosine > 0, phi, cosine) # when theta not in [0,pi], use cosface instead
        else:
            phi = torch.where(cosine > self.th, phi, cosine - self.mm)

        return cosine, phi


class ArcfaceLoss(nn.Module):
    def __init__(self, s=25):
        super(ArcfaceLoss, self).__init__()
        self.cross_entry = nn.CrossEntropyLoss()
        self.s = s

    def forward(self, input, label):
        cosine, phi = input
        cosine = self.s * cosine
        phi = self.s * phi

        one_hot = torch.zeros(cosine.size(), device='cuda')
        one_hot.scatter_(1, label.view(-1, 1).long(), 1)
        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
        loss = self.cross_entry(output, label)

        return loss