import torch
import torch.nn as nn


def make_model(args, parent=False):
    return MSR_RDN(args)


class RDB_Conv(nn.Module):
    def __init__(self, inChannels, growRate, kSize=3):
        super(RDB_Conv, self).__init__()
        Cin = inChannels
        G = growRate
        self.conv = nn.Sequential(*[
            nn.Conv2d(Cin, G, kSize, padding=(kSize - 1) // 2, stride=1),
            nn.ReLU()
        ])

    def forward(self, x):
        out = self.conv(x)
        return torch.cat((x, out), 1)


class RDB(nn.Module):
    def __init__(self, growRate0, growRate, nConvLayers, kSize=3):
        super(RDB, self).__init__()
        G0 = growRate0
        G = growRate
        C = nConvLayers

        convs = []
        for c in range(C):
            convs.append(RDB_Conv(G0 + c * G, G))
        self.convs = nn.Sequential(*convs)

        # Local Feature Fusion
        self.LFF = nn.Conv2d(G0 + C * G, G0, 1, padding=0, stride=1)

    def forward(self, x):
        return self.LFF(self.convs(x)) + x


class MSR_RDN(nn.Module):
    def __init__(self, args):
        super(MSR_RDN, self).__init__()
        G0 = args.G0
        kSize = args.RDNkSize

        # number of RDB blocks D, conv layers within the blocks C, out channels G within the last layer of the blocks,
        self.D, C, G = {
            'A': (20, 6, 32),
            'B': (16, 8, 64),
            'C': (6, 8, 32),
            'D': (2,4,16)
        }[args.RDNconfig]

        # Shallow feature extraction net
        self.SFENet1 = nn.Conv2d(3, G0, kSize, padding=(kSize - 1) // 2, stride=1)
        self.SFENet2 = nn.Conv2d(G0, G0, kSize, padding=(kSize - 1) // 2, stride=1)

        # Redidual dense blocks and dense feature fusion
        self.RDBs = nn.ModuleList()
        for i in range(self.D):
            self.RDBs.append(
                RDB(growRate0=G0, growRate=G, nConvLayers=C)
            )

        # Global Feature Fusion
        self.GFF = nn.Sequential(*[
            nn.Conv2d(self.D * G0, G0, 1, padding=0, stride=1),
            nn.Conv2d(G0, G0, kSize, padding=(kSize - 1) // 2, stride=1)
        ])
        self.OutLayer1 = nn.Conv2d(64, 1, 3, padding=1, stride=1, bias=False)
        self.OutLayer2 = nn.Conv2d(64, 1, 3, padding=1, stride=1, bias=False)
        self.OutLayer3 = nn.Conv2d(64, 1, 3, padding=1, stride=1, bias=False)
        self.OutLayer4 = nn.Conv2d(64, 1, 3, padding=1, stride=1, bias=False)
    def forward(self, inp_x, dist, num):
        f__1 = self.SFENet1(inp_x)
        x = self.SFENet2(f__1)
        RDBs_out = []
        for i in range(self.D):
            x = self.RDBs[i](x)
            RDBs_out.append(x)
        x = self.GFF(torch.cat(RDBs_out, 1))
        x += f__1
        # weights = []
        # inp_feature = nn.functional.unfold(x, 3, padding=1)
        out1 = self.OutLayer1(x)
        out2 = self.OutLayer2(x)
        out3 = self.OutLayer3(x)
        out4 = self.OutLayer4(x)

        return torch.cat([out1, out2, out3, out4], 1)
