import cv2
from b2b.eval.funcs import tensor2img

def check_blurry(self, image):
    def normalized_variance_of_laplacian(image):
        laplacian = cv2.Laplacian(image, cv2.CV_64F)
        var = laplacian.var()
        height, width = image.shape[:2]
        return var / (height * width)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    fm = normalized_variance_of_laplacian(gray)
    return fm

def filtering(self, input):
    blur_deg = []
    # blur_deg1 = []
    calc_blur = self.check_blurry
    # calc_blur = {0: self.self_shift, 
    #              1: self.detect_blur_fft,
    #              2: self.check_blurry}

    for each in input:
        blur_deg.append(calc_blur[method](tensor2img(each)))
        # blur_deg1.append(self.detect_blur_fft(each))

    sorted_indices = sorted(range(len(blur_deg)), key=lambda i: blur_deg[i] , reverse=True)
    # sorted_indices1 = sorted(range(len(blur_deg1)), key=lambda i: blur_deg1[i])
    return input[sorted_indices]

def set_two_domain_input(images, inputs, domain, device):
    if (domain is None) or (domain == 'both'):
        images.real_a = inputs[0]['img'].to(device, non_blocking = True)
        images.real_a = filtering(images.real_a).to(device, non_blocking = True)
        images.real_b = inputs[1]['img'].to(device, non_blocking = True)[:images.real_a.shape[0]]

        if len(inputs) == 4:
            images.real_c = inputs[2]['img'].to(device, non_blocking = True)[:images.real_a.shape[0]]
            images.real_d = inputs[3]['img'].to(device, non_blocking = True)[:images.real_a.shape[0]]

    elif domain in [ 'a', 0 ]:
        images.real_a = inputs.to(device, non_blocking = True)

    elif domain in [ 'b', 1 ]:
        images.real_b = inputs.to(device, non_blocking = True)
    
    elif domain in [ 'c', 2 ]:
        images.real_c = inputs.to(device, non_blocking = True)

    elif domain in [ 'd', 4 ]:
        images.real_d = inputs.to(device, non_blocking = True)

    else:
        raise ValueError(
            f"Unknown domain: '{domain}'."
            " Supported domains: 'a' (alias 0), 'b' (alias 1), or 'both'"
        )

