import copy
from tkinter import *
from PIL import ImageTk, Image, ImageOps


class ImagePlaceholder:
    def __init__(self, image_window, images):
        self.is_break = False
        self.current_image = None
        self.current_original_image = None
        self.image_window = image_window
        self.images = images.copy()

        self.image_label = Label(self.image_window.window)
        self.image_label.bind('<Configure>', lambda event: self.apply_options())
        self.image_label.pack(side=TOP, fill=BOTH, expand=1)

    def display_new_image(self):
        image_path = self.images.pop(0)
        if image_path == "break":
            self.is_break = True
            image_path = 'assets/images/break.jpg'
            self.image_window.play_elevator()
        else:
            self.is_break = False
            self.image_window.elevator_sound.stop()
        self.current_original_image = Image.open(image_path)
        self.current_image = copy.deepcopy(self.current_original_image)
        self.apply_options()

    def resize_image(self, reload=False):
        ma = self.image_window.window.winfo_toplevel()
        w, h = ma.winfo_width(), ma.winfo_height()

        if w < 21 or h < 21:
            w = 1280
            h = 1024
        self.current_image.thumbnail((w - 20, h - 20), Image.ANTIALIAS)

        if reload:
            self.load_widget()

    def apply_options(self):
        self.current_image = copy.deepcopy(self.current_original_image)

        if self.image_window.option["bw"]:
            self.current_image = self.current_image.convert("L")

        if self.image_window.option["mirror"]:
            self.current_image = ImageOps.mirror(self.current_image)

        self.resize_image(True)

    def load_widget(self):
        image_to_display = ImageTk.PhotoImage(self.current_image)
        self.image_label.configure(bg="#e8d4bc" if self.is_break else "#FFFFFF")
        self.image_label.configure(image=image_to_display)
        self.image_label.image = image_to_display
