"""
Utils to mix and generate new images
"""
import numpy as np
from PIL import Image
from PIL import ImageFilter
from keras_preprocessing.image import img_to_array

def generate_backgroud(image, k=16):
    """
    For each image, generate one purely background image.
    - The background image is generated by taking four corners of the orginal image then dilate.
    :param images: input image list
    :param k: the number pixels from corner patches to dilate the background
    :return: Background images for each image
    """
    w, h = image.shape[0], image.shape[1]
    # get four coner pathes of the image
    tl = image[:k, :k, :]
    tr = image[:k, -k:, :]
    bl = image[-k:, :k, :]
    br = image[-k:, -k:, :]

    # conbine the corner patch into one small image
    top = np.concatenate((tl, tr), axis=1)
    bot = np.concatenate((bl, br), axis=1)
    comb = np.concatenate((top, bot), axis=0)

    # dilate the image to the orignal size
    small = Image.fromarray(np.uint8(comb), mode='RGB')
    full = small.resize(size=(w, h), resample=Image.NEAREST)

    return img_to_array(full)


if __name__ == '__main__':
    img = Image.open('plots/gradcam_orig_6.jpg')
    print(img.size)
    img = img.resize(size=(224, 224))
    img.show()
    img = img_to_array(img)

    img_new = np.ones_like(img)*255
    ratio = 0.3
    k = int(ratio*224)
    w, h = img.shape[0], img.shape[1]
    # get four coner pathes of the image
    tl = img[:k, :k, :]
    print(tl.shape)
    tr = img[:k, -k:, :]
    print(tr.shape)
    bl = img[-k:, :k, :]
    print(bl.shape)
    br = img[-k:, -k:, :]
    print(br.shape)

    img_new[:k, :k, :] = img[:k, :k, :]
    img_new[-k:, :k, :] = img[-k:, :k, :]
    img_new[:k, -k:, :] = img[:k, -k:, :]
    img_new[-k:, -k:, :] = img[-k:, -k:, :]

    # conbine the corner patch into one small image
    top = np.concatenate((tl, tr), axis=1)
    print(top.shape)
    bot = np.concatenate((bl, br), axis=1)
    print(bot.shape)
    comb = np.concatenate((top, bot), axis=0)
    print(comb.shape)

    # dilate the image to the orignal size
    corner = Image.fromarray(np.uint8(img_new), mode='RGB')
    corner.save('plots/corners.png')
    corner.show()

    small = Image.fromarray(np.uint8(comb), mode='RGB')
    full = small.resize(size=(w, h), resample=Image.NEAREST)
    # kernel = (
    # 1, 1, 1,
    # 1, 0, 1,
    # 1, 1, 1,
    # )
    # full = full.filter(ImageFilter.Kernel(size=(3, 3), kernel=kernel))
    full = full.filter(ImageFilter.GaussianBlur)
    print(full.size)
    full.save('plots/corners_dilated.png')
    full.show()



