import torch
import torch.nn as nn
from modules.spike_layer import *

# configration
cfg = {
    'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}


class VGG(nn.Module):
    def __init__(self, vgg_name, timestep, sync_norm, act_func=LIF, num_classes=100):
        super(VGG, self).__init__()

        self.timestep = timestep
        self.sync_norm = sync_norm
        self.act_func_lif = act_func(tau=4.0, timestep=self.timestep, v_threshold=0.5, detach_reset=True, backend='cupy')
        self.features = self._make_layers(cfg[vgg_name])
        self.fc = nn.Sequential(
            nn.Linear(512, 512),
            act_func(tau=4.0, v_threshold=0.5, timestep=timestep, detach_reset=True, backend='cupy'),
            nn.Dropout(0.25),

            nn.Linear(512, 256),
            act_func(tau=4.0, v_threshold=0.5, timestep=timestep, detach_reset=True, backend='cupy'),
            nn.Dropout(0.25),

            nn.Linear(256, num_classes)
        )

    def _make_layers(self, cfg):
        layers = []
        in_channels = 3
        for x in cfg:
            if x == 'M':
                #  Not require Average Pooling for SNN
                 layers += [nn.AvgPool2d(2)]
                # continue
            else:
                layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),
                           tdBatchNorm(nn.BatchNorm2d(x), self.sync_norm),
                           self.act_func_lif]
                in_channels = x
        return nn.Sequential(*layers)

    def forward(self, x):
        B, C, H, W = x.shape
        x = (x.unsqueeze(0)).repeat(self.timestep, 1, 1, 1, 1)
        x = x.flatten(0, 1)

        x = self.features(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)  # time augmented

        x= x.reshape(self.timestep, B, -1)
        o = x.mean(0)
        return o, x  # [bs*2, D], [T, bs*2, D]


def get_vgg_spiking(name, timestep, sync_norm, act_func, num_classes):
    vggs_spiking = {
        "vgg11": VGG('VGG11', timestep, sync_norm, act_func, num_classes),
        "vgg16": VGG('VGG16', timestep, sync_norm, act_func, num_classes),
        "vgg19": VGG('VGG19', timestep, sync_norm, act_func, num_classes),
    }
    if name not in vggs_spiking.keys():
        raise KeyError(f"{name} is not a valid VGG version")
    return vggs_spiking[name]
