# Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
import torch.nn.functional as F

from .cls_head import ClsHead
from .contrastive_head import ContrastiveHead
from configs.losses import *


class LinearClsHead(ClsHead):
    """Linear classifier head.

    Args:
        num_classes (int): Number of categories excluding the background
            category.
        in_channels (int): Number of channels in the input feature map.
        init_cfg (dict | optional): The extra init config of layers.
            Defaults to use dict(type='Normal', layer='Linear', std=0.01).
    """

    def __init__(self,
                 num_classes,
                 in_channels,
                 init_cfg=dict(type='Normal', layer='Linear', std=0.01),
                 *args,
                 **kwargs):
        super(LinearClsHead, self).__init__(init_cfg=init_cfg, *args, **kwargs)

        self.in_channels = in_channels
        self.num_classes = num_classes

        if self.num_classes <= 0:
            raise ValueError(
                f'num_classes={num_classes} must be a positive integer')

        self.fc = nn.Linear(self.in_channels, self.num_classes)

    def pre_logits(self, x):
        if isinstance(x, tuple):
            x = x[-1]
        return x

    def simple_test(self, x, softmax=True, post_process=False):
        """Inference without augmentation.

        Args:
            x (tuple[Tensor]): The input features.
                Multi-stage inputs are acceptable but only the last stage will
                be used to classify. The shape of every item should be
                ``(num_samples, in_channels)``.
            softmax (bool): Whether to softmax the classification score.
            post_process (bool): Whether to do post processing the
                inference results. It will convert the output to a list.

        Returns:
            Tensor | list: The inference results.

                - If no post processing, the output is a tensor with shape
                  ``(num_samples, num_classes)``.
                - If post processing, the output is a multi-dimentional list of
                  float and the dimensions are ``(num_samples, num_classes)``.
        """
        x = self.pre_logits(x)
        cls_score = self.fc(x)

        if softmax:
            pred = (
                F.softmax(cls_score, dim=1) if cls_score is not None else None)
        else:
            pred = cls_score

        if post_process:
            return self.post_process(pred)
        else:
            return pred

    def forward_train(self, x, gt_label, **kwargs):
        x = self.pre_logits(x)
        cls_score = self.fc(x)
        losses = self.loss(cls_score, gt_label, **kwargs)
        return losses

class MultiLossLinearClsHead(LinearClsHead):
    def __init__(self,
                 num_classes,
                 in_channels,
                 proj_dim=128,
                 temperature=0.7,
                 loss_cls=dict(type='CrossEntropyLoss', loss_weight=1.0),
                 loss_contrastive=dict(type='ProjectedContrastiveLoss', loss_weight=0.5),
                 **kwargs):
        super().__init__(num_classes=num_classes, in_channels=in_channels, **kwargs)

        self.contrastive_head = ContrastiveHead(in_dim=in_channels, proj_dim=proj_dim)
        self.loss_cls_cfg = loss_cls
        self.loss_contrastive_cfg = loss_contrastive

        self.ce_loss = nn.CrossEntropyLoss()
        self.contrastive_loss = ProjectedContrastiveLoss(temperature=temperature)

    def forward_train(self, x, gt_label, x2=None, **kwargs):
        # x: view1 feature (B, C)
        # x2: view2 feature (optional, for contrastive)
        x = self.pre_logits(x)
        cls_score = self.fc(x)

        losses = dict()
        losses['loss_cls'] = self.ce_loss(cls_score, gt_label)

        # Contrastive
        if x2 is not None:
            x2 = self.pre_logits(x2)
            z1 = self.contrastive_head(x)
            z2 = self.contrastive_head(x2)
            losses['loss_contrast'] = self.contrastive_loss(z1, z2)

        return losses
