import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from collections import OrderedDict

from models.ew import *

class EW1ResNet(nn.Module):
    def __init__(self, block, num_blocks, num_classes=10):
        super(EW1ResNet, self).__init__()
        self.in_planes = 64

        self.conv1 = conv3x3(3,64)
        self.bn1 = nn.BatchNorm2d(64)
        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
        self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
        self.linear = nn.Linear(512*block.expansion, num_classes)

    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return nn.Sequential(*layers)

    def forward(self, x, mask=None, lin=0, lout=6):
        out = x
        if lin < 1 and lout > -1:
            out = self.conv1(out)
            out = self.bn1(out)
            out = F.relu(out)
        if lin < 2 and lout > 0:
            out = self.layer1(out)
        if lin < 3 and lout > 1:
            out = self.layer2(out)
        if lin < 4 and lout > 2:
            out = self.layer3(out)
        if lin < 5 and lout > 3:
            out = self.layer4(out)
        # if lout > 4:
        #     out = F.avg_pool2d(out, 4)
        #     out = out.view(out.size(0), -1)
        #     out = self.linear(out)
        if lin < 6 and lout > 4:
            out = F.avg_pool2d(out, 4)
            out = out.view(out.size(0), -1)
        if lout > 5:
            out = self.linear(out)
        return out


def EW1ResNet18(num_classes=10):
    return EW1ResNet(EWBasicBlock, [2,2,2,2], num_classes)

def EW1ResNet34(num_classes):
    return EW1ResNet(EWBasicBlock, [3,4,6,3], num_classes)

def EW1ResNet50(num_classes):
    return EW1ResNet(EWBottleneck, [3,4,6,3], num_classes)

def EW1ResNet101(num_classes):
    return EW1ResNet(EWBottleneck, [3,4,23,3], num_classes)

def EW1ResNet152(num_classes):
    return EW1ResNet(EWBottleneck, [3,8,36,3], num_classes)



# test()
