import os

import numpy as np
import torch
import torchvision.transforms as transforms
from PIL import Image

from .models import create_model


def tensor2im(input_image, imtype=np.uint8):
    if not isinstance(input_image, np.ndarray):
        if isinstance(input_image, torch.Tensor):  # get the data from a variable
            image_tensor = input_image.data
        else:
            return input_image
        image_numpy = image_tensor[0].cpu().float().numpy()  # convert it into a numpy array
        if image_numpy.shape[0] == 1:  # grayscale to RGB
            image_numpy = np.tile(image_numpy, (3, 1, 1))
        image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0  # post-processing: tranpose and scaling
    else:  # if it is a numpy array, do nothing
        image_numpy = input_image
    return image_numpy.astype(imtype)


def save_image(image_numpy, image_path, w, h, aspect_ratio=1.0):
    """Save a numpy image to the disk

    Parameters:
        image_numpy (numpy array) -- input numpy array
        image_path (str)          -- the path of the image
    """

    image_pil = Image.fromarray(image_numpy)
    image_pil = image_pil.resize((w, h))
    image_pil.save(image_path)


def save_img(image_tensor, w, h, filename):
    image_pil = tensor2im(image_tensor)

    save_image(image_pil, filename, w, h, aspect_ratio=1.0)
    print("Image saved as {}".format(filename))


def load_img(filepath):
    img = Image.open(filepath).convert('L')
    # print(img.size)
    width = img.size[0]
    height = img.size[1]
    # img = img.resize((512, 512), Image.BICUBIC)
    return img, width, height


if __name__ == '__main__':
    img_A = "/workspace/Semi_ref2sketch_code/datasets/ref_unpair/testA/real_Dress_732caedc416a0cbfedd0e6528040eac7.jpg_Img.jpg"
    img_B = "/workspace/Semi_ref2sketch_code/datasets/ref_unpair/testC/style_3.png"
    from opt import Config

    opt = Config()  # get  test options
    # hard-code some parameters for test
    opt.num_threads = 0  # test code only supports num_threads = 0
    opt.batch_size = 1  # test code only supports batch_size = 1
    opt.serial_batches = True  # disable data shuffling; comment this line if results on randomly chosen images are needed.
    opt.no_flip = True  # no flip; comment this line if results on flipped images are needed.
    opt.display_id = -1  # no visdom display; the test code saves the results to a HTML file.
    device = torch.device("cuda:0")
    model = create_model(opt)  # create a model given opt.model and other options
    model.setup(opt)
    transform_list = [transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]
    transform = transforms.Compose(transform_list)
    if opt.eval:
        model.eval()
    data = {}
    print(os.getcwd())
    B = reference, _, _ = load_img(r"/app/service/image2sketch/datasets/ref_unpair/testC/style_3.png")
    style_img = transform(reference)
    data['B'] = style_img
    data['B'] = data['B'].unsqueeze(0).to(device)
    A = Image.open(r"E:\workspace\trinity_client_aida\app\service\image2sketch\datasets\ref_unpair\testA\real_Dress_3200fecdc83d0c556c2bd96aedbd7fbf.jpg_Img.jpg")
    width = A.size[0]
    height = A.size[1]
    # data['A'] = A.resize((512, 512))
    data['A'] = transform(A)
    data['A'] = data['A'].unsqueeze(0).to(device)
    model.set_input(data)
    model.test()  # run inference
    visuals = model.get_current_visuals()  # get image results
    save_img(visuals['content_output'].cpu(), width, height, "result/result.jpg")
