import torch
import torch.nn as nn
from torch_geometric.nn import global_mean_pool
from torch_geometric.graphgym.models.layer import MLP, new_layer_config


class GNNGraphHead(nn.Module):
    """
    Reference: https://github.com/rampasek/GraphGPS
    """

    def __init__(self, dim_in, dim_out, cfg):
        super().__init__()
        self.layer_post_mp = MLP(
            new_layer_config(dim_in, dim_out, cfg.gnn.layers_post_mp, has_act=False, has_bias=True, cfg=cfg)
        )
        self.pooling_fun = global_mean_pool

    def _apply_index(self, batch):
        return batch.graph_feature, batch.y

    def forward(self, batch,aug=False):
        if aug == False:
            graph_emb = self.pooling_fun(batch.x, batch.batch)
            h_embedding = graph_emb.clone()
            graph_emb = self.layer_post_mp(graph_emb)
            batch.graph_feature = graph_emb
            pred, label = self._apply_index(batch)
            return h_embedding,pred, label
        else:
            graph_emb = self.layer_post_mp(batch.graph_emb)
            batch.graph_feature = graph_emb
            pred, label = self._apply_index(batch)
            return pred, label

    def embedding(self, batch):
        with torch.no_grad():
            graph_emb = self.pooling_fun(batch.x, batch.batch)
        return graph_emb


head_dict = {"graph": GNNGraphHead}
