import tkinter as tk
from tkinter import filedialog
from tkinter import BOTTOM, RIDGE, RIGHT, Label, Menu, Toplevel, ttk
from tkinter.font import NORMAL
from tkinter.messagebox import showinfo
from tkinter.filedialog import askopenfilename
from tkinter import DISABLED

import csv
import xlsxwriter
import tkinter


import pandas as pd
import sys
import os
from Skript.lang.run_LR_SBERT import main as backend


class App(ttk.Frame):

    def __init__(self, parent):
        ttk.Frame.__init__(self)

        # Make the app responsive
        for index in [0, 1, 2]:
            self.columnconfigure(index=index, weight=1)
            self.rowconfigure(index=index, weight=1)


        #Create a label
        self.label = tk.Label(root, text="Please upload an Excel file:", font=("Arial", 12, "bold"))

        # Create a Frame for input widgets
        self.widgets_frame = ttk.Frame(self)
        self.widgets_frame.grid(
            row=1, column=1, sticky="nsew", rowspan=8
        )
        self.widgets_frame.columnconfigure(index=0, weight=1)
        root.lift(self.widgets_frame)

        # Set Menu list
        self.menubar = Menu(root)
        root.configure(menu=self.menubar)
        self.options_menu = Menu(self.menubar)
        self.options_menu.add_command(label='Fenster schließen', command=root.destroy)
        self.options_menu.add_cascade(label='Optionen', menu=self.options_menu)

        # create labelframe for the file names read in 
        labelframe = tk.LabelFrame(self.widgets_frame, text="Input File", height=80, width=300, font=("Segoeui 10"))
        labelframe.grid(row=25, column=0, padx=1, pady=15, sticky="nsew")
        text = tk.Label(labelframe, text="", font=("Segoeui  10"))
        text.pack()
        labelframe.update()

        # open filechooser for .csv-files, set the state for the "Start" button1 and show infoboxes
        self.csv_file_path = ""

        def import_csv_data():
            csv_file_path = askopenfilename(
                title="Open .csv file", initialdir='Dokumente', filetypes=(
                    ("Excel files", "*.xlsx"), ("csv files", "*.csv"), ("tsv files", "*.tsv"), ("all files", "*.*")))
            # update the labelframe with the file cut down to only filename w/o path
            text.configure(text=os.path.basename(csv_file_path))
            # windows path:
            csv_file_path = csv_file_path.replace("/", "\\")

            indexIdent = csv_file_path

            # Set environment for output.csv files
            output_str = 'Skript\\outputs\\test.tsv'

            # Windows path:
            output_str = resource_path(output_str)

            # Excel files are parsed into csv files
            if indexIdent.endswith('.xlsx'):

                # Check if file exists
                if os.path.exists(csv_file_path):
                    # showinfo(title="debug_info", message=output_str + "\n" + indexIdent)
                    read_file = pd.read_excel(indexIdent)
                    read_file.to_csv(output_str, index=None, header=True, quoting=csv.QUOTE_NONE, escapechar="\t",
                                     sep='\t')

                    # when the input data has been loaded, highlight the Start button to indicate that
                    # grading can now commence
                    self.style = ttk.Style(self)
                    self.style.configure('Wild.TButton', font=('Helvetica', 14, 'bold'),
                                         foreground='green')

                    self.button1.config(state=NORMAL, style='Wild.TButton')
                    print(self.button1.winfo_class())

                    labelframe.update()
                    root.update()
                    print(self.button1.winfo_class())

                else:
                    showinfo(
                        title="Information",
                        message="File " + csv_file_path + " could not be found."
                        # message="Please choose a file"
                    )



            else:
                showinfo(
                    title="Information",
                    message="File " + csv_file_path + " could not be opened. Is it an Excel Sheet?"
                    # message="Please choose a file"
                )

        # New output window for showing the content of a csv file

        def open_new_window():
            new_window = Toplevel(root)
            new_window.protocol("WM_DELETE_WINDOW", new_window.destroy)
            new_window.title("ASYST Evaluated Results")
            new_window.geometry("850x500")
            new_window.iconbitmap(resource_path("icon.ico"))
            lab = Label(new_window, text="Results\n\nClick on Save As button below to view the file",
                        font=("Segoeui 20 bold"))
            lab.pack(padx=0, pady=35)


            save_button = ttk.Button(new_window, text="Save as ...", command=save_as_excel)
            save_button.pack(side=BOTTOM, expand=True)


        def save_as_excel():

            csvfile = "Skript\\outputs\\predictions.txt"
            name = "predictions.xlsx"

            # for Windows:
            csvfile = resource_path(csvfile)

            t = tkinter.filedialog.asksaveasfile(initialfile=name, mode='w',
                                                 filetypes=[("All Files", "*.*"), ("Excel Files", "*.xlsx")],
                                                 defaultextension=".xlsx")

            if t is not None:  # Check if the user didn't click Cancel
                file_path = t.name  # Save the location of the saved file
                # print(file_path)

            workbook = xlsxwriter.Workbook(t.name)

            # changes here for format highlight correct and incorrect

            cell_format1 = workbook.add_format()
            cell_format1.set_pattern(1)  # This is optional when using a solid fill.
            cell_format1.set_bg_color('green')
            cell_format1.set_bold()

            cell_format2 = workbook.add_format()
            cell_format2.set_pattern(1)  # This is optional when using a solid fill.
            cell_format2.set_bg_color('red')
            cell_format2.set_bold()

            worksheet = workbook.add_worksheet()
            with open(csvfile, 'rt', encoding='utf8') as f:
                reader = csv.reader(f, delimiter="\t")
                for r, row in enumerate(reader):
                    for c, col in enumerate(row):
                        if col == "correct":
                            worksheet.write(r, c, col, cell_format1)
                        elif col == "incorrect":
                            worksheet.write(r, c, col, cell_format2)
                        else:
                            worksheet.write(r, c, col)

            workbook.close()
            t.close()
            os.startfile(file_path)

        def start_progress():

            # Initializing busy state for cursor
            root.config(cursor="wait")
            self.button1.config(state=DISABLED)
            self.button2.config(state=DISABLED)
            root.update()

            backend()

            self.button1.config(state=NORMAL)
            self.button2.config(state=NORMAL)
            root.update()
            root.config(cursor="")
            # Evaluation window
            open_new_window()

        self.button2 = ttk.Button(self.widgets_frame, text="Input file", command=import_csv_data, state="normal")
        self.button2.grid(row=9, column=0, padx=5, pady=10, sticky="nsew")

        self.label = tk.Label(self.widgets_frame, text="Please upload an Excel file:", font=("Arial", 12, "bold"))
        self.label.grid(row=5, column=0, padx=5, pady=10, sticky="w")

        self.button1 = ttk.Button(self.widgets_frame, text="Start",
                                  command=start_progress,
                                  state=tk.DISABLED)
        self.button1.grid(row=12, column=0, padx=1, pady=5, sticky="nsew")


def resource_path(relative_path):
    if getattr(sys, 'frozen', False):
        # running in a bundle
        bundle_dir = sys._MEIPASS
    else:
        bundle_dir = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(bundle_dir, relative_path)


# Override stdout and stderr with NullWriter in GUI --noconsole mode
# This allows us to avoid a bug where tqdm try to write on NoneType
# https://github.com/tqdm/tqdm/issues/794
class NullWriter:
    def write(self, data):
        pass
    def flush(self):
        pass


if __name__ == "__main__":

    # Override stdout and stderr with NullWriter in GUI --noconsole mode
    # This allows us to avoid a bug where tqdm try to write on NoneType
    # https://github.com/tqdm/tqdm/issues/794
    if sys.stdout is None:
        sys.stdout = NullWriter()

    if sys.stderr is None:
        sys.stderr = NullWriter()

    root = tk.Tk()
    root.title("ASYST")

    # Set the theme

    root.tk.call("source", resource_path("azure.tcl"))
    root.tk.call("set_theme", "light")

    app = App(root)
    app.pack(fill="both", expand=True)

    root.update()
    root.geometry("850x600")

    root.iconbitmap(resource_path("icon.ico"))

    # stop the program completely upon closing the window
    root.protocol("WM_DELETE_WINDOW", root.destroy)

    root.mainloop()