from functools import partial
from customtkinter import *
from src.entity.config import Config
from src.entity.session.drawing import DrawingElement
from src.entity.session.breakEntity import BreakElement
from src.util import Util


class SessionWindow:
    def __init__(self, app):
        self.total_row_time_value_label = None
        self.down_button = None
        self.up_button = None
        self.timer_input = None
        self.number_of_drawings_input = None
        self.selected_element_index = -1
        self.delete_button = None
        self.add_button = None
        self.app = app

        self.window = CTkToplevel(app.root)
        self.window.title("Custom session")
        self.window.geometry("600x600")
        self.window.protocol("WM_DELETE_WINDOW", self.save_on_closing)

        self.left_column = CTkFrame(self.window, width=300, height=60)
        self.right_column = CTkFrame(self.window, width=300, height=600)

        self.left_column.pack(padx=10, pady=10, side=LEFT, fill=BOTH, expand=True)
        self.right_column.pack(padx=10, pady=10, side=LEFT, fill=BOTH, expand=True)

        self.list_in_session = []

    def open(self):
        list = Config._CONFIG['session']
        if list:
            self.list_in_session = [DrawingElement(e) if e["type"] == "Drawing" else BreakElement(e) for e in list]
        self.update_session_list()

    def update_session_list(self):
        self.reset_list()
        for i, session in enumerate(self.list_in_session):
            if isinstance(session, DrawingElement):
                new_session = CTkButton(self.left_column,
                                        text=session.number_of_drawings + " drawings of " + Util.format_seconds(int(session.timer)) + " each",
                                        command=partial(self.edit_element, i),
                                        fg_color=(
                                            Util.get_default_button_color() if i == self.selected_element_index else Util.get_default_active_button_color())
                                        )
            elif isinstance(session, BreakElement):
                new_session = CTkButton(self.left_column,
                                        text="Break of " + Util.format_seconds(int(session.timer)) + " each",
                                        command=partial(self.edit_element, i),
                                        fg_color=(
                                            Util.get_default_button_color() if i == self.selected_element_index else Util.get_default_active_button_color())
                                        )
            else:
                raise Exception("unknown type.")

            new_session.grid(row=i, column=0)

        buttons = CTkSegmentedButton(
            self.left_column, values=["+", "-", "☕", "^", "v", "save"],
            command=self.button_command
        )
        buttons.grid()

    def button_command(self, command):
        if command == "+":
            self.add_element()
        elif command == "-":
            self.remove_element()
        elif command == "^":
            self.up_element()
        elif command == "v":
            self.down_element()
        elif command == "save":
            self.save_session()
        elif command == "☕":
            self.add_break()
        else:
            print("unknown command")

    def reset_element(self):
        for widget in self.right_column.winfo_children():
            widget.destroy()

    def reset_list(self):
        for widget in self.left_column.winfo_children():
            widget.destroy()

    def update_element(self, index=None):
        self.reset_element()
        if index is not None:
            self.selected_element_index = index
            element = self.list_in_session[self.selected_element_index]
            self.update_session_list()
        else:
            element = DrawingElement()

        if isinstance(element, DrawingElement):
            self.print_drawing_form(element)
        elif isinstance(element, BreakElement):
            self.print_break_form(self.selected_element_index)

    def print_drawing_form(self, element):
        number_of_drawings_label = CTkLabel(self.right_column, text="Number of drawings")
        number_of_drawings_label.pack()

        self.number_of_drawings_input = CTkEntry(self.right_column)
        self.number_of_drawings_input.insert(INSERT, element.number_of_drawings)
        self.number_of_drawings_input.bind("<KeyRelease>", lambda e: self.update_local_timer(e))
        self.number_of_drawings_input.pack()
        self.number_of_drawings_input.focus_set()

        timer_label = CTkLabel(self.right_column, text="Time per drawing in seconds")
        timer_label.pack()

        self.timer_input = CTkEntry(self.right_column)
        self.timer_input.insert(INSERT, element.timer)
        self.timer_input.bind("<KeyRelease>", lambda e: self.update_local_timer(e))
        self.timer_input.pack()

        total_row_time_label = CTkLabel(self.right_column, text="Total row time")
        total_row_time_label.pack()
        self.total_row_time_value_label = CTkLabel(self.right_column, text="")
        self.total_row_time_value_label.pack()
        self.update_local_timer()

        save_button = CTkButton(self.right_column, text="Save", command=self.save)
        save_button.pack()

    def update_local_timer(self, event=None):
        self.total_row_time_value_label.configure(
            text=Util.format_seconds(int(self.timer_input.get()) * int(self.number_of_drawings_input.get()))
        )

    def remove_element(self):
        self.list_in_session.pop(self.selected_element_index)
        self.selected_element_index = -1
        self.update_session_list()

    def edit_element(self, i):
        self.update_element(i)

    def add_element(self):
        self.selected_element_index = -1
        self.update_session_list()
        self.update_element()

    def up_element(self):
        self.list_in_session.insert(self.selected_element_index - 1,
                                    self.list_in_session.pop(self.selected_element_index))
        self.selected_element_index -= 1
        self.update_session_list()

    def down_element(self):
        self.list_in_session.insert(self.selected_element_index + 1,
                                    self.list_in_session.pop(self.selected_element_index))
        self.selected_element_index += 1
        self.update_session_list()

    def save(self, element_type="Drawing"):
        if element_type == "Drawing":
            element = DrawingElement() if self.selected_element_index < 0 \
                else self.list_in_session[self.selected_element_index]
            element.timer = self.timer_input.get()
            element.number_of_drawings = self.number_of_drawings_input.get()
        elif element_type == "Break":
            element = BreakElement() if self.selected_element_index < 0 \
                else self.list_in_session[self.selected_element_index]
            element.timer = self.timer_input.get()
        else:
            raise Exception("unknown type.")

        if self.selected_element_index < 0:
            self.list_in_session.append(element)
        else:
            self.list_in_session[self.selected_element_index] = element

        self.update_session_list()
        self.selected_element_index = -1
        self.reset_element()

    def save_on_closing(self):
        # TODO save
        self.window.destroy()

    def save_session(self):
        Config._CONFIG['session'] = []
        for element in self.list_in_session:
            Config._CONFIG['session'].append(element.__dict__)
        Config.save()
        self.app.set_custom(self.list_in_session)
        self.window.destroy()

    def add_break(self):
        self.selected_element_index = -1
        self.update_session_list()
        self.print_break_form()

    def print_break_form(self, index=None):
        self.reset_element()
        if index is not None:
            self.selected_element_index = index
            element = self.list_in_session[self.selected_element_index]
            self.update_session_list()
        else:
            element = BreakElement()

        timer_label = CTkLabel(self.right_column, text="Time for this break in seconds")
        timer_label.pack()

        self.timer_input = CTkEntry(self.right_column)
        self.timer_input.insert(INSERT, element.timer)
        self.timer_input.pack()

        save_button = CTkButton(self.right_column, text="Save", command=partial(self.save, "Break"))
        save_button.pack()
