# GUI to ArchiveDataCompare Skript
from tkinter import filedialog
from tkinter import *
import os
import queue
import threading
import DiscomDataExportLibrary as Pcl
import tkinter.font as font
import ArchiveDataContentCompare
import tkinter.scrolledtext as scrolledtext
master = Tk()
master.title("Archive Data Compare Tool")

# We start with to File Dialog to select one Archive as reference to be compared with one or more Archives
# We initialize and set the Dialogs to change the Archives
# 1 Reference Archive
Archive1Label = Label(master, text="Reference Archive:").grid(row=0, column=0, columnspan=1, rowspan=1)
Archive1 = StringVar(master, value="")
Archive1Entry = Entry(master, textvariable = Archive1, width=200).grid(row=0, column=1, columnspan=4, rowspan=1, sticky=W+E+N+S)
def A1Dlg():
    initdir = "C:/Discom/Measurement/Multirot"
    if(str(Archive1.get()) != ""):
        initdir = os.path.dirname(str(Archive1.get()))
    elif(str(Archive2.get()) != ""):
        initdir = os.path.dirname(str(Archive2.get()))
    Archive1Dlg =  filedialog.askopenfilename(initialdir = initdir,title = "Select Archive", filetypes = (("Archives","*.rdt"),("all files","*.*")))
    Archive1.set(Archive1Dlg)
Archive1SearchButton = Button(master, text='Select Archive', width=25, command=A1Dlg).grid(row=0, column=5, columnspan=1, rowspan=1)
# 2 List of Archives
Archive2Label = Label(master, text="Compare Archive:").grid(row=1, column=0, columnspan=1, rowspan=1)
Archive2 = StringVar(master, value="")
# Second variable is a list of strings
Archive2_list = Variable(master,value=[])
#listbox1 = tk.Listbox(self, listvariable=self.lb1_values)
Archive2Entry = Entry(master, textvariable = str(Archive2_list), width=200).grid(row=1, column=1, columnspan=4, rowspan=1, sticky=W+E+N+S)
def A2Dlg():
    initdir = "C:/Discom/Measurement/Multirot"
    if(str(Archive2.get()) != ""):
        initdir = os.path.dirname(str(Archive2.get()))
    elif(str(Archive1.get()) != ""):
        initdir = os.path.dirname(str(Archive1.get()))
    # Here we use askopenfilenames instead of askopenfile, since we want a list of filenames
    Archive2Dlg =  filedialog.askopenfilenames(initialdir = initdir,title = "Select Archive", filetypes = (("Archives","*.rdt"),("all files","*.*")))
    Archive2_list.set(Archive2Dlg)
    #print(Archive2_list)
    #Set Archive2 to first element of list, so we don't break the previous code
    Archive2.set(Archive2Dlg[0])
Archive2SearchButton = Button(master, text='Select Archive', width=25, command=A2Dlg).grid(row=1, column=5, columnspan=1, rowspan=1)
# CheckBox if we want to write a Diff File
WriteToFile = IntVar()
WriteToFileButton = Checkbutton(master, text='Diff File:', variable=WriteToFile).grid(row=2, column=0, columnspan=1, rowspan=1)
# Entry with a Path to the Diff File we want to write
PathEntry = StringVar(master, value="")
FilePathEntry = Entry(master, textvariable = PathEntry, width=200).grid(row=2, column=1, columnspan=4, rowspan=1, sticky=W+E+N+S)
def FDlg():
    initdir = "/"
    if(str(PathEntry.get()) != ""):
        initdir = os.path.dirname(str(PathEntry.get()))
    elif(str(PlotPathEntry.get()) != ""):
        initdir = os.path.dirname(str(PlotPathEntry.get()))
    elif(str(Archive1.get()) != ""):
        initdir = os.path.dirname(str(Archive1.get()))
    elif(str(Archive2.get()) != ""):
        initdir = os.path.dirname(str(Archive2.get()))
    FPDlg =  filedialog.askdirectory(initialdir = initdir,title = "SelectFilePath")
    filePath = FPDlg + "/DiffFile.txt"
    PathEntry.set(filePath)
FilePathSearchButton = Button(master, text='Select Folder', width=25, command=FDlg).grid(row=2, column=5, columnspan=1, rowspan=1)
# CheckBox if we want to plot a the Differences
PlotDifferences = IntVar()
PlotDifferencesButton = Checkbutton(master, text='Diff Plots', variable=PlotDifferences).grid(row=3, column=0, columnspan=1, rowspan=1)
# Entry with a Path to the Diff File we want to write
PlotPathEntry = StringVar(master, value="")
FolderPlotPathEntry = Entry(master, textvariable = PlotPathEntry, width=200).grid(row=3, column=1, columnspan=4, rowspan=1, sticky=W+E+N+S)
def PDlg():
    initdir = "/"
    if(str(PlotPathEntry.get()) != ""):
        initdir = os.path.dirname(str(PlotPathEntry.get()))
    elif(str(PathEntry.get()) != ""):
        initdir = os.path.dirname(str(PathEntry.get()))
    elif(str(Archive1.get()) != ""):
        initdir = os.path.dirname(str(Archive1.get()))
    elif(str(Archive2.get()) != ""):
        initdir = os.path.dirname(str(Archive2.get()))
    PDlg =  filedialog.askdirectory(initialdir = initdir,title = "SelectFilePath")
    filePath = PDlg
    PlotPathEntry.set(filePath)
PlotPathSearchButton = Button(master, text='Select Folder', width=25, command=PDlg).grid(row=3, column=5, columnspan=1, rowspan=1)
# Output Message Queue
OutputMessageLabel = Label(master, text="Output Message").grid(row=4, column=2, columnspan=1, rowspan=1)
MT = scrolledtext.ScrolledText(master, undo = True, height = 10)
MT['font'] = ('consolas','12')
MT.grid(row=5, column=0, columnspan=6, rowspan=5, sticky=W+E)
message_queue = queue.Queue()
message_event = threading.Event()
def PumpMessage(message_event):
    while True:
        message_event.wait()
        try:
            while True:
                message = message_queue.get(False)
                if message is not None:
                    text = "{}\n"
                    text = text.format(message)
                    MT.insert("end",text)
                    MT.see("end")
        except queue.Empty:
            pass
        message_event.clear()
MessageThread = threading.Thread(target = PumpMessage, args=(message_event,))
MessageThread.daemon = True
MessageThread.start()
# Entry for the Clavis Filter
Clavis_Label = Label(master, text="Clavis Filter:", font='Helvetica 12 bold').grid(row=10, column=0, columnspan=1, rowspan=1)
Clavis_ModeLabel = Label(master, text="Mode").grid(row=11, column=0, columnspan=1, rowspan=1)
Clavis_Mode = Entry(master)
Clavis_Mode.insert(END,"*")
Clavis_Mode.grid(row=11, column=1, columnspan=1, rowspan=1)
Clavis_InstrumentLabel = Label(master, text="Instrument").grid(row=12, column=0, columnspan=1, rowspan=1)
Clavis_Instrument = Entry(master)
Clavis_Instrument.insert(END,"*")
Clavis_Instrument.grid(row=12, column=1, columnspan=1, rowspan=1)
Clavis_ParameterLabel = Label(master, text="Parameter").grid(row=13, column=0, columnspan=1, rowspan=1)
Clavis_Parameter = Entry(master)
Clavis_Parameter.insert(END,"*")
Clavis_Parameter.grid(row=13, column=1, columnspan=1, rowspan=1)
Clavis_IChannelLabel = Label(master, text="Channel").grid(row=14, column=0, columnspan=1, rowspan=1)
Clavis_IChannel = Entry(master)
Clavis_IChannel.insert(END,"*")
Clavis_IChannel.grid(row=14, column=1, columnspan=1, rowspan=1)
Clavis_SignalLabel = Label(master, text="Signal").grid(row=15, column=0, columnspan=1, rowspan=1)
Clavis_Signal = Entry(master)
Clavis_Signal.insert(END,"*")
Clavis_Signal.grid(row=15, column=1, columnspan=1, rowspan=1)
Clavis_LocationLabel = Label(master, text="Location").grid(row=16, column=0, columnspan=1, rowspan=1)
Clavis_Location = Entry(master)
Clavis_Location.insert(END,"*")
Clavis_Location.grid(row=16, column=1, columnspan=1, rowspan=1)
# Entry for the Absolute Tolerance
ToleranceLabel = Label(master, text="Tolerance:", font='Helvetica 12 bold').grid(row=17, column=0, columnspan=1, rowspan=1)
Absolute_ToleranceLabel = Label(master, text="Absolute Tolerance").grid(row=18, column=0, columnspan=1, rowspan=1)
Absolute_Tolerance = Entry(master)
Absolute_Tolerance.insert(END,0)
Absolute_Tolerance.grid(row=18, column=1, columnspan=1, rowspan=1)
# Entry for the Absolute Tolerance
Relative_ToleranceLabel = Label(master, text="Relative Tolerance").grid(row=19, column=0, columnspan=1, rowspan=1)
Relative_Tolerance = Entry(master)
Relative_Tolerance.insert(END,0)
Relative_Tolerance.grid(row=19, column=1, columnspan=1, rowspan=1)
# Funktion to Execute the Script with the current settings
def ExecuteDiffScript():
    T.delete('1.0', END)
    T.configure(background = 'yellow')
    T.insert(END,"Processing...")
    T.update()
    try:
        if(bool(PlotDifferences.get())):
            for filename in os.listdir(str(PlotPathEntry.get())):
                file_path = os.path.join(str(PlotPathEntry.get()), filename)
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    if file_path.lower().endswith(".png"):
                        os.unlink(file_path)
        clavis = Pcl.Quinter(str(Clavis_Mode.get()),str(Clavis_Instrument.get()),str(Clavis_Parameter.get()),str(Clavis_IChannel.get()),str(Clavis_Signal.get()),str(Clavis_Location.get()))
        ClavisList = ArchiveDataContentCompare.RunExecution(str(Archive1.get()),Archive2_list.get(),float(Absolute_Tolerance.get()),float(Relative_Tolerance.get()),bool(WriteToFile.get()),str(PathEntry.get()),bool(PlotDifferences.get()),str(PlotPathEntry.get()),clavis,message_queue,message_event)
        T.delete('1.0', END)
        T.update()
        if(len(ClavisList) < 1):
            T.configure(background = 'green')
            T.insert(END, "Every Value equal within Tolerance\n")
        else:
            T.configure(background = 'red')
            text = "Differences Found: {}\n"
            text = text.format(len(ClavisList))
            T.insert(END, text)
            for clavis in ClavisList:
                text = "{}\n"
                text = text.format(clavis.QuinterText())
                T.insert(END,text)
    except:
        T.delete('1.0', END)
        T.update()
        T.configure(background = 'orange')
        T.insert(END, "Something gone Wrong:\n")
        T.insert(END, sys.exc_info()[1])
def Evaluate():
    if( (str(Archive1.get()) != "") and (str(Archive1.get()) != "") ):
        ExecThread = threading.Thread(target = ExecuteDiffScript)
        ExecThread.daemon = True
        ExecThread.start()
    else:
        T.delete('1.0', END)
        T.update()
        T.configure(background = 'orange')
        T.insert(END, "Something gone Wrong:\n")
        T.insert(END, "Two Archive Pathes and Tolerance is least needed.")
# Button to Execute Diff
myFont = font.Font(family='Helvetica')
EvaluateButton = Button(master, text='Evaluate Differences', bg='#0052cc', fg='#ffffff', command=Evaluate)
EvaluateButton['font'] = myFont
EvaluateButton.grid(row=20, column=0, columnspan=2, rowspan=1, sticky = E+W)
# Report Window
ReportLabel = Label(master, text="Report:").grid(row=10, column=3, columnspan=1, rowspan=1)
T = scrolledtext.ScrolledText(master, undo = True, height = 10)
T['font'] = ('consolas','12')
T.grid(row=11, column=2, columnspan=4, rowspan=11, sticky = N+E+W+S)
# Exit and Clear
def ExitAndClear():
    master.quit()
    master.destroy()
# Button to Exit the Program
ExitButton = Button(master, text='Exit', font='Helvetica 12 bold',command=ExitAndClear).grid(row=21, column=0, columnspan=2, rowspan=1, sticky = E+W)
# Main
mainloop()