import random
from tkinter import *

from customtkinter import CTkToplevel
from pygame import mixer
from src.element.image import ImagePlaceholder
from src.element.toolbar import Toolbar


class ImageWindow:
    def __init__(self, app):
        self.current_original_image = None
        self.app = app

        self.window = CTkToplevel(app.root)
        self.window.title("Image")
        self.window.geometry("1280x1024")
        self.window.protocol("WM_DELETE_WINDOW", self.on_closing)

        self.option = {
            "bw": False,
            "mirror": False,
            "always_on_top": False,
            "fullscreen": False,
        }

        mixer.init()
        self.countdown_sound = mixer.Sound('assets/sounds/countdown.mp3')

        self.images = []
        self.current_image = None
        self.image_label = None
        toolbar = Frame(self.window, bd=1, relief=RAISED)
        toolbar.pack(side=BOTTOM, fill=X)
        self.timer = 0

        self.toolbar = Toolbar(self, self.timer)
        self.image = ImagePlaceholder(self, self.images)

    def on_closing(self):
        self.countdown_sound.stop()
        self.window.destroy()

    def next_image(self):
        if self.toolbar.timer_check is not None:
            self.window.after_cancel(self.toolbar.timer_check)
        self.image.display_new_image()
        self.toolbar.display_new_timer()

    def lets_draw(self, images, timer):
        random.shuffle(images)
        final_images = []
        timers = []
        if self.app.custom:
            for element in self.app.list_in_session:
                if element.type == "Drawing":
                    for number in range(int(element.number_of_drawings)):
                        timers.append(int(element.timer))
                        final_images.append(images.pop(0))
                else:
                    timers.append(int(element.timer))
                    final_images.append("break")
            self.image.images = final_images
        else:
            for i in images:
                timers.append(timer)
            self.image.images = images

        self.toolbar.timers = timers
        self.next_image()

    def play_countdown(self):
        self.countdown_sound.play()
