import tkinter as tk
from tkinter import BOTTOM, RIDGE, RIGHT, Label, Menu, Toplevel, ttk
from tkinter.messagebox import showwarning
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 sentence_transformers
import pandas as pd
import sys
import os
from Skript.english.run_SAG_mnli import main as english_backend
from Skript.german.run_LR_SBERT import main as german_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 value list
        self.combo_list = ["Choose language of input data", "English", "German"]

        # 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 outputwinodow 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("1920x1080")
                new_window.iconbitmap(resource_path("icon.ico"))
                lab = Label(new_window, text="Results", font=("Segoeui 20 bold"))
                lab.pack(padx=0, pady=35)
                container = ttk.Frame(new_window)
                canvas = tk.Canvas(container)
                scrollbary = ttk.Scrollbar(container, orient='vertical', command=canvas.yview)
                scrollbar = ttk.Scrollbar(container, orient="horizontal", command=canvas.xview)
                scrollable_frame = ttk.Frame(canvas)
                scrollable_frame.bind(
                    "<Configure>",
                    lambda e: canvas.configure(
                        scrollregion=canvas.bbox("all")
                    )
                )
                canvas.configure(scrollregion=canvas.bbox("all"))
                canvas.create_window((4, 4), window=scrollable_frame)

                csv_file_path = resource_path("Skript\\outputs\\predictions.txt");

                # Read the csv file and parse it into the table

                with open((csv_file_path), "r", newline="", encoding="utf8") as f:

                    reader = csv.reader(f, delimiter="\t")
                    r = 0
                    for col in reader:
                        c = 0
                        for row in col:
                            # variable column width
                            col_width = 65
                            anch= 'center'
                            match c:
                                case 0:
                                    col_width = 10  # ID is short
                                    anch='w'
                                case 3:
                                    col_width = 20  # label is short
                                    anch='w'
                                case 4:
                                    col_width = 20  # label is short
                                    anch = 'w'

                            label = Label(scrollable_frame, width=col_width, height=4, text=row, wraplength=500, anchor=anch, relief=RIDGE,
                                          font=("Segoeui 10"))
                            label.grid(row=r + 1, column=c + 1)
                            string_c = "incorrect"
                            if string_c in row:
                                label.config(bg="red")
                            c += 1
                        r += 1
                canvas.config(height=500, width=1500, xscrollcommand=scrollbar.set, yscrollcommand=scrollbary.set)
                canvas.configure(xscrollcommand=scrollbar.set, yscrollcommand=scrollbary.set)
                scrollbary.pack(side=RIGHT, fill=tk.Y)
                scrollbar.pack(side=BOTTOM, fill=tk.X)

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

                container.pack(padx=30, pady=15,fill="both", expand=True)
                canvas.pack(fill="both", 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")
            workbook = xlsxwriter.Workbook(t.name)
            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):
                        worksheet.write(r, c, col)
            workbook.close()
            t.close()

        def start_progress():

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


            # start the correct backend pipeline
            if (self.combobox.get() == 'English'):
                showinfo(
                    title="Information",
                    message="Generating grade suggestions for English student answers. This may take a little while.")
                # run English backend
                english_backend()
            elif (self.combobox.get() == 'German'):
                showinfo(
                    title="Information",
                    message="Generating grade suggestions for German student answers. This may take a little while.")
                # run German/multilingual backend
                german_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=DISABLED)
        self.button2.grid(row=9, column=0, padx=5, pady=10, sticky="nsew")

        # select language, "Choose language" as default
        self.combobox = ttk.Combobox(
            self.widgets_frame, values=self.combo_list)
        self.combobox.current(0)
        self.combobox.grid(row=5, column=0, padx=5, pady=10, sticky="ew")

        # set state for button2("Input"-button) and if 'Spanish' is chosen in the combobox disable both buttons
        def set_buttons_state(event):
            self.button2.config(state="normal")
            # print('State changed')
            if (self.combobox.get() == 'Spanish'):
                showwarning(title="Information", message="Not available")
                self.button1.config(state="disabled")
                self.button2.config(state="disabled")

        # get events from changing combobox
        self.combobox.bind('<<ComboboxSelected>>', set_buttons_state)

        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

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()