import tkinter
from pathlib import Path
from tkinter import *
from tkinter import filedialog
import customtkinter
from src.entity.config import Config
from src.entity.generator import Generator
from src.util import Util
from src.window.about import AboutWindow
from src.window.image import ImageWindow
from src.window.session import SessionWindow
from CTkMenuBar import *


class App:
    def __init__(self, root):
        super().__init__()
        self.list_in_session = None
        self.custom = False
        self.config = Config()
        self.session = None
        self.session_window = None
        self.image_window = None
        self.root = root
        self.selected_folder = ""
        self.found_images = []
        self.timer = 0

        menu = CTkMenuBar(master=root)
        generate_button = menu.add_cascade("Generate")
        help_button = menu.add_cascade("Help")

        dropdown = CustomDropdownMenu(widget=generate_button)
        dropdown.add_option(option="Poses", command=lambda:self.download_poses('poses'))

        about = CustomDropdownMenu(widget=help_button)
        about.add_option(option="À propos", command=self.show_help)

        self.title = customtkinter.CTkLabel(root, text="Drawing Training")
        self.title.pack()

        self.folder_selector = customtkinter.CTkButton(root, text="Select a folder", command=self.select_folder)
        self.folder_selector.pack()

        self.folder_name = customtkinter.CTkLabel(root, text="Folder : " + self.selected_folder)
        self.folder_name.pack()

        self.images_len = customtkinter.CTkLabel(root, text="Found : " + str(len(self.found_images)))
        self.images_len.pack()

        self.button_frame = Frame(root, bg=root.cget("bg"))
        self.button_frame.pack(fill=X, expand=True)

        timers = [
            Util.format_seconds(30),
            Util.format_seconds(45),
            Util.format_seconds(60),
            Util.format_seconds(120),
            Util.format_seconds(300),
            Util.format_seconds(600),
            "Custom"
        ]

        self.buttons = []
        for i, timer in enumerate(timers):
            new_button = customtkinter.CTkButton(self.button_frame, width=10, text=timer,
                                                 command=lambda t=timer: self.set_timer_in_seconds(t))
            new_button.pack(side=tkinter.LEFT, fill=X, expand=True)
            self.buttons.append(new_button)

        self.launch_button = customtkinter.CTkButton(root, text="Let's draw!", command=self.lets_draw, state="disabled")
        self.launch_button.pack(side=tkinter.BOTTOM)

        self.read_config()

    def read_config(self):
        try:
            self.selected_folder = Config.get_required_config_var("default_folder")
            self.folder_name.configure(text="Folder : " + self.selected_folder)
            self.find_images_in_folder()
        except Exception:
            pass

    def show_help(self):
        AboutWindow(self)

    def lets_draw(self):
        self.image_window = ImageWindow(self)
        self.image_window.lets_draw(self.found_images.copy(), self.timer)

    def custom_session(self):
        self.session_window = SessionWindow(self)
        self.session_window.open()

    def select_folder(self):
        new_directory = filedialog.askdirectory()
        if new_directory:
            self.selected_folder = new_directory
            self.folder_name.configure(text="Folder : " + self.selected_folder)
            Config.set_config_var("default_folder", self.selected_folder).save()
            self.find_images_in_folder()
            self.check_lets_draw()

    def download_poses(self, generator=None):
        Generator(generator=generator, folder=self.selected_folder)
        self.find_images_in_folder()

    def find_images_in_folder(self):
        if Path(self.selected_folder).exists():
            self.found_images = list(
                p.resolve() for p in Path(self.selected_folder).glob("**/*") if p.suffix in {".jpg", ".gif", ".png"}
            )
            self.images_len.configure(text="Found : " + str(len(self.found_images)))

    def check_lets_draw(self):
        if self.selected_folder != "" and len(self.found_images) > 0 and (self.timer != 0 or self.custom):
            self.launch_button.configure(state="normal")
        else:
            self.launch_button.configure(state="disabled")

    def set_timer_in_seconds(self, user_data):
        # resetting buttons states
        for button in self.buttons:
            button.configure(fg_color=(Util.get_default_button_color() if user_data != button.cget(
                "text") else Util.get_default_active_button_color()))

        self.custom = False
        if user_data == "Custom":
            return self.custom_session()

        self.timer = Util.format_time_to_seconds(user_data)
        self.check_lets_draw()

    def set_custom(self, list_in_session):
        self.custom = True
        self.list_in_session = list_in_session
        self.check_lets_draw()
