import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import math
import sys
import numpy as np

def conv3x3(in_planes, out_planes, stride=1):
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)

def conv_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        init.xavier_uniform(m.weight, gain=np.sqrt(2))
        init.constant(m.bias, 0)
    elif classname.find('BatchNorm') != -1:
        init.constant(m.weight, 1)
        init.constant(m.bias, 0)

class wide_basic(nn.Module):
    def __init__(self, in_planes, planes, dropout_rate, stride=1):
        super(wide_basic, self).__init__()
        self.bn1 = nn.BatchNorm2d(in_planes)
        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, bias=True)
        self.dropout = nn.Dropout(p=dropout_rate)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=True)

        self.shortcut = nn.Sequential()
        if stride != 1 or in_planes != planes:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride, bias=True),
            )

    def forward(self, x):
        out = self.dropout(self.conv1(F.relu(self.bn1(x))))
        out = self.conv2(F.relu(self.bn2(out)))
        out += self.shortcut(x)

        return out

confs = {
    0: (True, True, True),
    1: (False, True, True),
    2: (False, False, True),
    3: (False, False, False),
    4: (True, False, True),
    5: (True, False, False),
    6: (True, True, False)
}


def init_weight(m):
    if type(m) == nn.Conv2d or type(m) == nn.Linear:
        torch.nn.init.kaiming_uniform_(m.weight, a=math.sqrt(5))
        fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(m.weight)
        bound = 1 / math.sqrt(fan_in)
        torch.nn.init.uniform_(m.bias, -bound,bound)


class WideResNet(nn.Module):
    def __init__(self, depth, widen_factor, dropout_rate, num_classes,
            noise_layer=0, noise_fc_layer=0, times=1, in_channels=3):
        super(WideResNet, self).__init__()
        self.in_planes = 16

        assert ((depth-4)%6 ==0), 'Wide-resnet depth should be 6n+4'
        n = (depth-4)/6
        k = widen_factor

        print('| Wide-Resnet %dx%d' %(depth, k))
        nStages = [16, 16*k, 32*k, 64*k]
        self.conv1 = conv3x3(in_channels,nStages[0])
        self.layer1 = self._wide_layer(wide_basic, nStages[1], n, dropout_rate, stride=1)
        self.layer2 = self._wide_layer(wide_basic, nStages[2], n, dropout_rate, stride=2)
        self.layer3 = self._wide_layer(wide_basic, nStages[3], n, dropout_rate, stride=2)
        self.bn1 = nn.BatchNorm2d(nStages[3], momentum=0.9)
        self.fcs = []
        for i in range(noise_fc_layer):
            in_dim = nStages[3] if i == 0 else nStages[3] * times
            out_dim = nStages[3] if i == (noise_fc_layer - 1) else nStages[3] * times
            linear = nn.Linear(in_dim, out_dim)
            linear.weight.requires_grad = False
            linear.bias.requires_grad = False
            self.fcs += [linear, nn.ReLU()]
        self.fcs.append(nn.Linear(nStages[3], num_classes))
        self.fcs = nn.Sequential(*self.fcs)
        #self.linear = nn.Linear(nStages[3], num_classes)
        grad_conf = confs[noise_layer]
        for m in self.layer1.modules():
            if isinstance(m, nn.Conv2d):
                m.weight.requires_grad = grad_conf[0]
                m.bias.requires_grad = grad_conf[0]
        for m in self.layer2.modules():
            if isinstance(m, nn.Conv2d):
                m.weight.requires_grad = grad_conf[1]
                m.bias.requires_grad = grad_conf[1]
        for m in self.layer3.modules():
            if isinstance(m, nn.Conv2d):
                m.weight.requires_grad = grad_conf[2]
                m.bias.requires_grad = grad_conf[2]

        self.apply(init_weight)

    def _wide_layer(self, block, planes, num_blocks, dropout_rate, stride):
        strides = [stride] + [1]*int(num_blocks-1)
        layers = []

        for stride in strides:
            layers.append(block(self.in_planes, planes, dropout_rate, stride))
            self.in_planes = planes

        return nn.Sequential(*layers)

    def forward(self, x):
        out = self.conv1(x)
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = F.relu(self.bn1(out))
        out = F.avg_pool2d(out, 8)
        out = out.view(out.size(0), -1)
        out = self.fcs(out)

        return out

    def forward_conv(self, x):
        out = self.conv1(x)
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = F.relu(self.bn1(out))
        out = F.avg_pool2d(out, 8)
        out = out.view(out.size(0), -1)
        return out

# https://github.com/meliketoy/wide-resnet.pytorch/blob/master/networks/wide_resnet.py
if __name__ == '__main__':
    net=WideResNet(28, 10, 0.3, 10)
    y = net(torch.randn(1,3,32,32))

    print(y.size())
