import torch.nn as nn
import torch
import torch.nn.functional as F
import math
import torch.utils.model_zoo as model_zoo


__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
           'resnet152']


model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}


def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)

        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class LinearStitch(nn.Module):
    def __init__(self,tg_layer_id,src_layer_id, tg_feat_size=48, src_feat_size=48):
        super(LinearStitch, self).__init__()
        self.tg_layer_id = tg_layer_id
        self.src_layer_id = src_layer_id
        self.tu = nn.Linear(tg_feat_size, 1)
        self.su = nn.Linear(src_feat_size, 1)
        # self.wt = torch.ones(2)*0.5
        self.wt = nn.Parameter(torch.ones(2) * 0.5)

    def forward(self, input1, input2):
        tw = input1.size(3)
        sw = input2.size(3)

        if sw !=tw:
            input2 = F.interpolate(
                input2,
                scale_factor=tw / sw,
                mode='bilinear'
            )
        # f1 = F.avg_pool2d(input1, input1.size(2)).view(-1, input1.size(1))
        # f2 = F.avg_pool2d(input2, input2.size(2)).view(-1, input2.size(1))
        # w0 = self.tu(f1)
        # w1 = self.su(f2)
        # self.wt = torch.stack([w0, w1])
        # # self.wt = F.softmax(self.wt, dim=0)
        # self.wt = F.softplus(self.wt)
        # y = self.wt[0].reshape(input1.size(0), 1, 1, 1) * input1 + self.wt[1].reshape(input2.size(0), 1, 1, 1) * input2
        y = self.wt[0] * input1 + self.wt[1] * input2
        # y = input1 + input2
        return y


class ShareableResidualLayer(nn.Sequential):

    def __init__(self, id, block, inplanes, planes, blocks, stride=1):
        self.id = id
        self.inplanes = inplanes
        self.num_blocks = blocks
        self.route_wts = []
        self.src_planes_sizes = [64, 64, 128, 256]

        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        super(ShareableResidualLayer, self).__init__(*layers)

        # Define ru and xs
        # self.lu = nn.Conv2d(inplanes, inplanes, 1)
        self.ru = nn.ModuleList([])
        self.ru.extend([nn.Sequential(
            nn.Conv2d(src_planes, inplanes, 1),
                nn.BatchNorm2d(inplanes),
            ) for src_planes in self.src_planes_sizes])

        # for src_planes in self.src_planes_sizes:
        #     downsample = None
        #     if src_planes != inplanes:
        #         downsample = nn.Sequential(
        #             nn.Conv2d(src_planes, inplanes,
        #                       kernel_size=1, stride=1, bias=False),
        #             nn.BatchNorm2d(inplanes),
        #         )
        #     self.ru.append(block(src_planes, inplanes, 1, downsample))

        self.cs = nn.ModuleList([])
        self.cs.extend([LinearStitch(id, i, inplanes, inplanes) for i in range(len(self.src_planes_sizes))])

    def forward(self, input, ref_inputs=None):
        output = input
        self.route_wts = []
        if ref_inputs is not None:
            assert isinstance(ref_inputs, list)
            assert len(ref_inputs) == len(self.ru)
            ref_out = []
            for ref, mod, xs in zip(ref_inputs, self.ru, self.cs):
                if ref is not None:
                    ref_out.append(xs(output, mod(ref)))
            ref_out = torch.stack(ref_out)
            output = torch.mean(ref_out, dim=0)
        for xs in self.cs:
            self.route_wts.append('{:.2f}'.format(xs.wt[0].mean().item()))
            self.route_wts.append('{:.2f}'.format(xs.wt[1].mean().item()))
        for idx in range(self.num_blocks):
            output = self._modules.get(str(idx))(output)
        return output


class ResNet(nn.Module):

    def __init__(self, block, layers, num_classes=1000, transfer_type=None):
        super(ResNet, self).__init__()

        self.num_classes = num_classes
        self.shareable_layers = [0, 1, 2, 3]
        self.shareable_layers_nout = [64, 64, 128, 256]

        self.inplanes = 64

        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

        if transfer_type is None:
            self.layer1 = self._make_layer(block, 64, layers[0])
            self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
            self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
            self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
        else:
            self.layer1 = ShareableResidualLayer(1, block, self.inplanes, 64, layers[0])
            self.inplanes = 64 * block.expansion
            self.layer2 = ShareableResidualLayer(2, block, self.inplanes, 128, layers[1], stride=2)
            self.inplanes = 128 * block.expansion
            self.layer3 = ShareableResidualLayer(3, block, self.inplanes, 256, layers[2], stride=2)
            self.inplanes = 256 * block.expansion
            self.layer4 = ShareableResidualLayer(4, block, self.inplanes, 512, layers[3], stride=2)
            self.inplanes = 512 * block.expansion

        self.avgpool = nn.AvgPool2d(7, stride=1)
        self.fc = nn.Linear(512 * block.expansion, num_classes)
        self.lwf = False

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x, ref_features=None, pairs=None):
        self.route_wts = []
        c0 = self.conv1(x)
        b0 = self.bn1(c0)
        r0 = self.relu(b0)
        p0 = self.maxpool(r0)

        if ref_features is None:
            f1 = self.layer1(p0)
            f2 = self.layer2(f1)
            f3 = self.layer3(f2)
            f4 = self.layer4(f3)
        else:
            assert pairs is not None
            s_feat = []
            input = p0
            layer_func = [self.layer1, self.layer2, self.layer3, self.layer4]
            for l in range(4):  # 0,1,2,3
                ref_inputs = []
                ct = 0
                for r in range(4):  # 0,1,2,3
                    if (l, r) in pairs:
                        ct += 1
                        ref_inputs.append(ref_features[r])
                    else:
                        ref_inputs.append(None)
                if ct == 0:
                    ref_inputs = None
                input = layer_func[l](input, ref_inputs)
                s_feat.append(input)
                self.route_wts.append(layer_func[l].route_wts)
            [f1, f2, f3, f4] = s_feat

        f5 = self.avgpool(f4)
        f5 = f5.view(f5.size(0), -1)
        out = self.fc(f5)
        # print('<>'.join([','.join(map(str, route_wts[i])) for i in range(len(route_wts))]))
        return out, [p0, f1, f2, f3, f4]

    def forward_with_features(self, x):
        return self.forward(x)


def resnet18(pretrained=False, transfer_type=None, **kwargs):
    """Constructs a ResNet-18 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [2, 2, 2, 2], transfer_type=transfer_type, **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))
    return model


def resnet34(pretrained=False, transfer_type=None, **kwargs):
    """Constructs a ResNet-34 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [3, 4, 6, 3], transfer_type=transfer_type, **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))
    return model


def resnet50(pretrained=False, transfer_type = None, **kwargs):
    """Constructs a ResNet-50 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 4, 6, 3], transfer_type=transfer_type, **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
    return model


def resnet101(pretrained=False, transfer_type = None, **kwargs):
    """Constructs a ResNet-101 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 4, 23, 3], transfer_type=transfer_type, **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))
    return model


def resnet152(pretrained=False, transfer_type = None, **kwargs):
    """Constructs a ResNet-152 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 8, 36, 3], transfer_type=transfer_type, **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
    return model
