"""Simple green-screening application.

This program prompts the user for images and green-screen parameters and generates
a new image with the background swapped out.

Author: CS 149 Instructors
Version: 2/27/2022
"""

from PIL import Image
import tkinter as tk
from tkinter import filedialog
import color_utils


def green_screen(original, replacement, green, threshold):
    """Swap out the background in a green-screen image.

    The original image will not be modified.

    Args:
        original (Image):  The original image (against a green screen)
        replacement (Image):  Image containing the new background
        green (tuple): 3-tuple representing the color of the green screen
                       background
        threshold (int): Threshold indicating how close the colors need to be to
                         swap out a pixel

    Returns:
        Image: A new image with the background replaced.

    """

    # First resize the replacement image to have the same scale as
    # The green-screen image.
    resize_ratio = max([original.width / replacement.width,
                        original.height / replacement.height])
    new_width = int(resize_ratio * replacement.width) + 1
    new_height = int(resize_ratio * replacement.height) + 1
    replacement = replacement.resize((new_width, new_height))

    # Create a copy of the original image, and then replace all of the "green"
    # pixels with the corresponding pixels from the replacement image.
    result = original.copy()
    for x in range(original.width):
        for y in range(original.height):
            px = original.getpixel((x, y))
            if color_utils.same_color(px, green, threshold):
                new_pixel = replacement.getpixel((x, y))
                result.putpixel((x, y), new_pixel)

    return result


def main():
    """Run the application."""
    root = tk.Tk()
    root.withdraw()

    print("Select a green-screen image jpeg...")
    file_green = filedialog.askopenfilename(title="Select A Green-Screen Image",
                                            initialdir="./",
                                            initialfile="face.jpg",
                                            filetypes=[("Image files", ".jpg .JPG")])

    print("Select a background image jpeg...")
    file_replace = filedialog.askopenfilename(title="Select A Background Image",
                                              initialdir="./",
                                              initialfile="king.jpg",
                                              filetypes=[("Image files", ".jpg .JPG")])

    red = int(input("Red channel for the greenscreen (default 203) : ") or "203")
    green = int(input("Green channel for the greenscreen (default 200) : ") or "200")
    blue = int(input("Blue channel for the greenscreen (default 195) : ") or "195")
    threshold = int(input("Enter a color difference threshold (default 30) : ") or "30")

    im = Image.open(file_green)
    replace = Image.open(file_replace)
    out = green_screen(im, replace, (red, green, blue), threshold)
    out.show()


if __name__ == "__main__":
    main()
    quit()
