""" dt_net_2d.py
    DeepThinking network 2D.

    Collaboratively developed
    by Avi Schwarzschild, Eitan Borgnia,
    Arpit Bansal, and Zeyad Emam.

    Developed for DeepThinking project
    October 2021
"""

import torch
from torch import nn

from .blocks import BasicBlock2D as BasicBlock

# Ignore statemenst for pylint:
#     Too many branches (R0912), Too many statements (R0915), No member (E1101),
#     Not callable (E1102), Invalid name (C0103), No exception (W0702)
# pylint: disable=R0912, R0915, E1101, E1102, C0103, W0702, R0914


class DTNet(nn.Module):
    """DeepThinking Network 2D model class"""

    def __init__(self, block, num_blocks, width, in_channels=3, recall=True, group_norm=False, n_thinker=4, **kwargs):
        super().__init__()
        self.n_thinker = n_thinker
        self.recall = recall
        self.width = int(width)
        self.group_norm = group_norm
        proj_conv = nn.Conv2d(in_channels, width * self.n_thinker, kernel_size=3,
                              stride=1, padding=1, bias=False)

        self.thinker = []
        self.thinker_1 = self._make_thinker(block, width, in_channels, num_blocks, recall)
        self.thinker_2 = self._make_thinker(block, width, in_channels, num_blocks, recall)
        self.thinker_3 = self._make_thinker(block, width, in_channels, num_blocks, recall)
        self.thinker_4 = self._make_thinker(block, width, in_channels, num_blocks, recall)
        self.thinker.append(self.thinker_1)
        self.thinker.append(self.thinker_2)
        self.thinker.append(self.thinker_3)
        self.thinker.append(self.thinker_4)

        head_conv1 = nn.Conv2d(width, 32, kernel_size=3,
                               stride=1, padding=1, bias=False)
        head_conv2 = nn.Conv2d(32, 8, kernel_size=3,
                               stride=1, padding=1, bias=False)
        head_conv3 = nn.Conv2d(8, 2, kernel_size=3,
                               stride=1, padding=1, bias=False)

        self.projection = nn.Sequential(proj_conv, nn.ReLU())
        # self.recur_block = nn.Sequential(*recur_layers)
        self.head = nn.Sequential(head_conv1, nn.ReLU(),
                                  head_conv2, nn.ReLU(),
                                  head_conv3)

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

    def _make_thinker(self, block, width, in_channels, num_blocks, recall=True):
        conv_recall = nn.Conv2d(width + in_channels, width, kernel_size=3,
                                    stride=1, padding=1, bias=False)

        recur_layers = []
        if recall:
            recur_layers.append(conv_recall)

        for i in range(len(num_blocks)):
            recur_layers.append(self._make_layer(block, width, num_blocks[i], stride=1))
        
        return nn.Sequential(*recur_layers)

    def forward(self, x, iters_to_do, interim_thought=None, **kwargs):
        initial_thought = self.projection(x)

        if interim_thought is None:
            interim_thought = initial_thought

        all_outputs = torch.zeros((x.size(0), iters_to_do, 2, x.size(2), x.size(3))).to(x.device)
    
        for i in range(iters_to_do):
            interim_thought_sum = torch.zeros((x.size(0), self.width, x.size(2), x.size(3))).to(x.device)
            for j in range(self.n_thinker):
                interim_thought_j = initial_thought[:, j * self.width : (j + 1) * self.width, :, :]
                if self.recall:
                    interim_thought_j = torch.cat([interim_thought_j, x], 1)
                interim_thought_j = self.thinker[j](interim_thought_j)
                interim_thought_sum = interim_thought_sum + interim_thought_j
            out = self.head(interim_thought_sum)
            all_outputs[:, i] = out

        if self.training:
            return out, interim_thought

        return all_outputs


def dt_net_2d(width, **kwargs):
    return DTNet(BasicBlock, [2], width=width, in_channels=kwargs["in_channels"], recall=False)


def dt_net_recall_2d(width, **kwargs):
    return DTNet(BasicBlock, [2], width=width, in_channels=kwargs["in_channels"], recall=True)


def dt_net_gn_2d(width, **kwargs):
    return DTNet(BasicBlock, [2], width=width, in_channels=kwargs["in_channels"], recall=False, group_norm=True)


def dt_net_recall_gn_2d(width, **kwargs):
    return DTNet(BasicBlock, [2], width=width, in_channels=kwargs["in_channels"], recall=True, group_norm=True)
