import tkinter as tk
from configparser import NoSectionError, NoOptionError
from tkinter import font, filedialog, messagebox

from config import Config


def show_error(message_title: str, message: str, parent: tk.Tk | tk.Toplevel):
    messagebox.showwarning(
        title=message_title,
        message=message,
        parent=parent
    )


class Window(tk.Toplevel):
    def __init__(self, parent, root: tk.Tk):
        super().__init__(root)
        self.parent = parent
        self.root = root
        self.protocol("WM_DELETE_WINDOW", self.close_window)
        self.bind("<Escape>", self.close_window)

    def close_window(self, event = None):
        self._destroy_window()

    def _destroy_window(self):
        self.root.update()
        self.destroy()


class EditRecord(Window):
    def __init__(self, parent, root: tk.Tk, data: tuple):
        super().__init__(parent, root)
        self.bind("<Return>", self._update)

        self.data = data
        button_width = 8
        self.title("Adresse bearbeiten")
        self.aktiv = tk.StringVar()
        self.firma = tk.StringVar()
        self.name = tk.StringVar()
        self.strasse = tk.StringVar()
        self.plz_ort = tk.StringVar()

        self.field_list = [self.aktiv, self.firma, self.name, self.strasse, self.plz_ort]
        for argument, field in zip(self.data, self.field_list):
            field.set(argument)

        edit_frame = tk.Frame(self)
        edit_frame.pack(side=tk.TOP, fill=tk.X, pady=20, padx=20)
        tk.Label(edit_frame, text="Aktiv", anchor=tk.W).grid(row=0, column=0)
        tk.Label(edit_frame, text="Firma").grid(row=0, column=1)
        tk.Label(edit_frame, text="Name").grid(row=0, column=2)
        tk.Label(edit_frame, text="Strasse").grid(row=0, column=3)
        tk.Label(edit_frame, text="Plz/Ort").grid(row=0, column=4)
        edit_aktiv = tk.Checkbutton(edit_frame, variable=self.aktiv, onvalue="x", offvalue="")
        edit_aktiv.grid(row=1, column=0)
        edit_firma = tk.Entry(edit_frame, textvariable=self.firma)
        edit_firma.grid(row=1, column=1)
        edit_name = tk.Entry(edit_frame, textvariable=self.name)
        edit_name.grid(row=1, column=2)
        edit_strasse = tk.Entry(edit_frame, textvariable=self.strasse)
        edit_strasse.grid(row=1, column=3)
        edit_plz_ort = tk.Entry(edit_frame, textvariable=self.plz_ort)
        edit_plz_ort.grid(row=1, column=4)

        button_frame = tk.Frame(self)
        button_frame.pack(side=tk.TOP, pady=10)
        tk.Button(button_frame, text="Save", command=self._update, width=button_width).pack(side=tk.LEFT)
        tk.Button(button_frame, text="Abbrechen", command=self.close_window, width=button_width).pack(side=tk.LEFT)

    def _update(self, event = None):
        self.parent.update_record(self.field_list)
        self.close_window()


class SettingsWindow(Window):
    def __init__(self, parent, root: tk.Tk):
        super().__init__(parent, root)
        self.geometry(f"500x330+{self.root.winfo_x() + 20}+{self.root.winfo_y() + 20}")
        self.config = Config()
        self.json_file = tk.StringVar()
        self.csv_file = tk.StringVar()

        title = font.Font(family='Ubuntu Mono', size=20, weight=font.BOLD)
        tk.Label(self, text="Einstellungen", font=title).pack(pady=20)

        path_frame = tk.Frame(self)
        path_frame.pack(pady=(10, 40))

        tk.Label(path_frame, text="Datenpfad JSON Datei").grid(row=0, column=0)
        tk.Entry(path_frame, textvariable=self.json_file, width=50).grid(row=1, column=0)
        tk.Button(path_frame, text="Pfad", command=lambda: self.set_json_path(self.json_file.get())).grid(row=1,
                                                                                                          column=1)

        tk.Label(path_frame, text="Datenpfad CSV Export Datei").grid(row=2, column=0)
        tk.Entry(path_frame, textvariable=self.csv_file, width=50).grid(row=3, column=0)
        tk.Button(path_frame, text="Pfad", command=lambda: self.set_csv_path(self.csv_file.get())).grid(row=3, column=1)

        bottom_frame = tk.Frame(self)
        bottom_frame.pack()
        tk.Button(bottom_frame, text="Ok", command=self.ok).pack(side=tk.LEFT)
        tk.Button(bottom_frame, text="Abbrechen", command=self.cancel).pack(side=tk.LEFT)

        self.load_config()

    def set_json_path(self, initial_dir: str = ""):
        initial_dir = "~/" if initial_dir == "" else initial_dir
        new_path = filedialog.askdirectory(initialdir=initial_dir, title="Datenpfad JSON Datei")
        new_path = initial_dir if len(new_path) == 0 else new_path
        self.json_file.set(new_path)

    def set_csv_path(self, initial_dir: str = ""):
        initial_dir = "~/" if initial_dir == "" else initial_dir
        new_path = filedialog.askdirectory(initialdir=initial_dir, title="Datenpfad CSV Datei")
        new_path = initial_dir if len(new_path) == 0 else new_path
        self.csv_file.set(new_path)

    def load_config(self):
        try:
            self.json_file.set(self.config.get("json", "path"))
        except NoSectionError:
            self.config.add_section("json")
            self.config.set("json", "path", "")
        except NoOptionError:
            self.config.set("json", "path", "")

        try:
            self.csv_file.set(self.config.get("csv", "path"))
        except NoSectionError:
            self.config.add_section("csv")
            self.config.set("csv", "path", "")
        except NoOptionError:
            self.config.set("csv", "path", "")

    def ok(self):
        if self.json_file.get() == "" or self.csv_file.get() == "":
            show_error(message_title="Fehlerhafte Konfiguration",
                       message="Pfad für JSON oder CSV Datei fehlt",
                       parent=self)
            return
        self.config.set("json", "path", self.json_file.get())
        self.config.set("csv", "path", self.csv_file.get())
        self.close_window()

    def cancel(self):
        self.close_window()
