"""Partially based on https://github.com/okankop/Efficient-3DCNNs/tree/master/models
For Inception3D - I3D - see https://github.com/tomrunia/PyTorchConv3D/blob/master/models/i3d.py"""

import math
from collections import OrderedDict
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange


class ResNet3D(nn.Module):
    def __init__(self, *, config, path_weights, block, layers, shortcut_type='B'):
        super(ResNet3D, self).__init__()

        self.config = config
        self.vs = dict()

        t = self.config["input_size"][0]
        if self.config["downscale"]:
            t = [round(s * d) for s, d in zip(t, self.config["downscale"][0])]
        self.vs["shape_in"] = t

        # depth_stride = 1
        # plane_stride = 2
        # depth_divider = 16
        # plane_divider  = 32
        if self.config["fe"]["l1_stride"] == 1:
            depth_stride = 1
            plane_stride = 1
            depth_divider = 16
            plane_divider = 16
        elif self.config["fe"]["l1_stride"] == 2:
            depth_stride = 2
            plane_stride = 2
            depth_divider = 32
            plane_divider = 32
        else:
            raise ValueError("Unsupported `l1_stride`")

        self.inplanes = 64  # INFO: this var is non-explicitly updated in _make_layer
        self.conv1 = nn.Conv3d(self.config["input_channels"], 64,
                               kernel_size=(7, 7, 7),
                               stride=(depth_stride, plane_stride, plane_stride),
                               padding=(3, 3, 3), bias=False)
        self.bn1 = nn.BatchNorm3d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool3d(kernel_size=(3, 3, 3), stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0], shortcut_type)
        self.layer2 = self._make_layer(block, 128, layers[1], shortcut_type, stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], shortcut_type, stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], shortcut_type, stride=2)

        last_shape = (int(math.ceil(self.vs["shape_in"][0] / plane_divider)),
                      int(math.ceil(self.vs["shape_in"][1] / plane_divider)),
                      int(math.ceil(self.vs["shape_in"][2] / depth_divider)))
        self.avgpool = nn.AvgPool3d((last_shape[2], last_shape[0], last_shape[1]), stride=1)
        self.fc = nn.Linear(512 * block.expansion, self.config["output_channels"])

        for m in self.modules():
            if isinstance(m, nn.Conv3d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out')
            elif isinstance(m, nn.BatchNorm3d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        if self.config["restore_weights"]:
            self.load_state_dict(torch.load(path_weights))

    def _make_layer(self, block, planes, blocks, shortcut_type, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            if shortcut_type == 'A':
                downsample = partial(downsample_basic_block,
                                     planes=planes * block.expansion,
                                     stride=stride)
            else:
                downsample = nn.Sequential(
                    nn.Conv3d(self.inplanes, planes * block.expansion,
                              kernel_size=1, stride=stride, bias=False),
                    nn.BatchNorm3d(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):
        endpoints = OrderedDict()

        # Code assumes: B, CH, S, R, C
        x = rearrange(x, "b ch r c s -> b ch s r c")

        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        endpoints["main"] = x
        return endpoints


def downsample_basic_block(x, planes, stride):
    out = F.avg_pool3d(x, kernel_size=1, stride=stride)
    zero_pads = torch.Tensor(out.size(0),
                             planes - out.size(1),
                             out.size(2),
                             out.size(3),
                             out.size(4)).zero_()
    if isinstance(out.data, torch.cuda.FloatTensor):
        zero_pads = zero_pads.cuda()
    out = torch.cat([out.data, zero_pads], dim=1)
    return out


class ResNet3DBasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(ResNet3DBasicBlock, self).__init__()
        self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm3d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv3d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm3d(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 ResNet3DBottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(ResNet3DBottleneck, self).__init__()
        self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm3d(planes)
        self.conv2 = nn.Conv3d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn2 = nn.BatchNorm3d(planes)
        self.conv3 = nn.Conv3d(planes, planes * self.expansion, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm3d(planes * self.expansion)
        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 ResNeXt3D(nn.Module):
    def __init__(self, *, config, path_weights, block, layers, shortcut_type='B',
                 cardinality=32):
        super(ResNeXt3D, self).__init__()

        self.config = config
        self.vs = dict()

        t = self.config["input_size"][0]
        if self.config["downscale"]:
            t = [round(s * d) for s, d in zip(t, self.config["downscale"][0])]
        self.vs["shape_in"] = t

        # depth_stride = 1
        # plane_stride = 2
        # depth_divider = 16
        # plane_divider  = 32
        depth_stride = 2
        plane_stride = 2
        depth_divider = 32
        plane_divider = 32

        self.inplanes = 64  # INFO: this var is non-explicitly updated in _make_layer
        self.conv1 = nn.Conv3d(self.config["input_channels"], 64,
                               kernel_size=(7, 7, 7),
                               stride=(depth_stride, plane_stride, plane_stride),
                               padding=(3, 3, 3), bias=False)
        self.bn1 = nn.BatchNorm3d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool3d(kernel_size=(3, 3, 3), stride=2, padding=1)
        self.layer1 = self._make_layer(block, 128, layers[0], shortcut_type, cardinality)
        self.layer2 = self._make_layer(block, 256, layers[1], shortcut_type, cardinality, stride=2)
        self.layer3 = self._make_layer(block, 512, layers[2], shortcut_type, cardinality, stride=2)
        self.layer4 = self._make_layer(block, 1024, layers[3], shortcut_type, cardinality, stride=2)

        last_shape = (int(math.ceil(self.vs["shape_in"][0] / plane_divider)),
                      int(math.ceil(self.vs["shape_in"][1] / plane_divider)),
                      int(math.ceil(self.vs["shape_in"][2] / depth_divider)))
        self.avgpool = nn.AvgPool3d((last_shape[2], last_shape[0], last_shape[1]), stride=1)
        self.fc = nn.Linear(cardinality * 32 * block.expansion, self.config["output_channels"])

        for m in self.modules():
            if isinstance(m, nn.Conv3d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out')
            elif isinstance(m, nn.BatchNorm3d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        if self.config["restore_weights"]:
            self.load_state_dict(torch.load(path_weights))

    def _make_layer(self, block, planes, blocks, shortcut_type, cardinality, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            if shortcut_type == 'A':
                downsample = partial(downsample_basic_block,
                                     planes=planes * block.expansion, stride=stride)
            else:
                downsample = nn.Sequential(
                    nn.Conv3d(self.inplanes, planes * block.expansion,
                              kernel_size=1, stride=stride, bias=False),
                    nn.BatchNorm3d(planes * block.expansion))

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

        return nn.Sequential(*layers)

    def forward(self, x):
        endpoints = OrderedDict()

        # Code assumes: B, CH, S, R, C
        x = rearrange(x, "b ch r c s -> b ch s r c")

        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        endpoints["main"] = x
        return endpoints


class ResNeXt3DBottleneck(nn.Module):
    expansion = 2

    def __init__(self, inplanes, planes, cardinality, stride=1, downsample=None):
        super(ResNeXt3DBottleneck, self).__init__()
        mid_planes = cardinality * int(planes / 32)
        self.conv1 = nn.Conv3d(inplanes, mid_planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm3d(mid_planes)
        self.conv2 = nn.Conv3d(mid_planes, mid_planes, kernel_size=3, stride=stride,
                               padding=1, groups=cardinality, bias=False)
        self.bn2 = nn.BatchNorm3d(mid_planes)
        self.conv3 = nn.Conv3d(mid_planes, planes * self.expansion, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm3d(planes * self.expansion)
        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


def ResNet3D10(**kwargs):
    model = ResNet3D(block=ResNet3DBasicBlock, layers=[1, 1, 1, 1], **kwargs)
    return model


def ResNet3D18(**kwargs):
    model = ResNet3D(block=ResNet3DBasicBlock, layers=[2, 2, 2, 2], **kwargs)
    return model


def ResNet3D34(**kwargs):
    model = ResNet3D(block=ResNet3DBasicBlock, layers=[3, 4, 6, 3], **kwargs)
    return model


def ResNet3D50(**kwargs):
    model = ResNet3D(block=ResNet3DBottleneck, layers=[3, 4, 6, 3], **kwargs)
    return model


def ResNet3D101(**kwargs):
    model = ResNet3D(block=ResNet3DBottleneck, layers=[3, 4, 23, 3], **kwargs)
    return model


def ResNet3D152(**kwargs):
    model = ResNet3D(block=ResNet3DBottleneck, layers=[3, 8, 36, 3], **kwargs)
    return model


def ResNet3D200(**kwargs):
    model = ResNet3D(block=ResNet3DBottleneck, layers=[3, 24, 36, 3], **kwargs)
    return model


def ResNeXt3D50(**kwargs):
    model = ResNeXt3D(block=ResNeXt3DBottleneck, layers=[3, 4, 6, 3], **kwargs)
    return model


def ResNeXt3D101(**kwargs):
    model = ResNeXt3D(block=ResNeXt3DBottleneck, layers=[3, 4, 23, 3], **kwargs)
    return model


def ResNeXt3D152(**kwargs):
    model = ResNeXt3D(block=ResNeXt3DBottleneck, layers=[3, 8, 36, 3], **kwargs)
    return model
