'''--------------------------------------------------------------------------------------------------
Die View bildet die Oberflaeche ab. 
Sie ist in 3 Sektoren Top, Main und ButtonFrame unterteilt. Der TopFrame beihnahltet die Taskleiste, 
der Button Frame gibt Informationen raus. Im Main Frame sind die Buttons yu starten und stoppen der 
Buchstabierungen. HIerfuer sind extra Seiten erstellt, die beliebig, je nach Situation ausgetauscht 
werden koennen
'''

try: 
    from Tkinter import *           #Fuer Python 2.7
    import tkFileDialog as fd
except ImportError:                 #Fuer Python >3
    from tkinter import *
    from tkinter import filedialog as fd

from UIController import *



class View(Tk):
    def __init__(self, c, path_default, *args, **kwargs):
        '''--------------------------------------------------------------------------------------------------
        In der Init wird das Lazout gesetyt und die Funktionen yur erstellung der Frames aufgerufen,
        zudem wird dem schliesen des Fensters sowie den anpassen der Groesse andere Funktionen hinterlegt
        '''
        Tk.__init__(self, *args, **kwargs)
        self.controller = c
        self.PATH_DEFAULT = path_default
        self.title("Visuelles Buchstabieren")
        self.h = 1000
        self.w = 2000  
        self.geometry('{}x{}'.format(self.w,self.h))
        self.faktor = [(0.073),(0.727), (0.2)]
        #self.resizable(height=False, width= False)
        self.layout = {
            "background": "#00001E",
            "backgroundBtn": "#1C86EE",
            "fontColor": "#FFFFFF",
            "backgroundBar": "#00002E",
            "font": ('Calibri', 20, 'bold'),
            "fontSmall": ('Calibri', 14, 'bold'),
            "fontInfo": ('Calibri', 25)
        }

        self.createTopFrame()
        self.createMainFrame()
        self.createBottomFrame()

        self.bind("<Configure>", self.adjustSize)
        self.protocol("WM_DELETE_WINDOW", self.onClosing)
    
      
    def changeFrame(self, pageName):
        '''--------------------------------------------------------------------------------------------------
        Setzt dem Frame passend zum pageName in den Vordergrund
        '''
        frame = self.frames[pageName]
        frame.tkraise()

    def adjustSize(self, event):
        '''--------------------------------------------------------------------------------------------------
        passt nach Faktoren die einyelnen Seitenteile der jeweiligen Frame Groesse an
        '''
        if(str(event.widget) =="."):
            self.h = event.height
            self.w = event.width
            self.topFrame.configure(height=(self.h*self.faktor[0]), width=self.w)
            self.mainFrame.configure(height=(self.h*self.faktor[1]), width=self.w)
            self.bottomFrame.configure(height=(self.h*self.faktor[2]), width=self.w)
            self.container.configure(height=(self.h*self.faktor[1]), width=self.w)
            for f in self.frames:
                self.frames[f].configure(height=(self.h*self.faktor[1]), width=self.w)
                self.frames[f].adjustSize(height=(self.h*self.faktor[1]), width=self.w)


    def onClosing(self):
        '''--------------------------------------------------------------------------------------------------
        Stoppt alle laufenden Threads und schliesst OpenVibe und den Aquisitionserver bevor sich das Fenster 
        schliesst
        '''
        print("closing")
        self.controller.commandStop()
        self.controller.stopAcquisitionServer()
        print("destroy")
        try:
            self.dialog.destroy()
        except:
            pass
        self.destroy()
        
    
    def createTopFrame(self):
        '''--------------------------------------------------------------------------------------------------
        Erstellt die Buttons und Textfelder fuer die Taskleiste und positionier diese im Frame
        '''
        self.topFrame = Frame(self, bg=self.layout["backgroundBar"], height=50, width=500) 
        self.changeBtn = Button(self.topFrame, text="Wechsel zu taktilen BCI", command=lambda: self.controller.actionPerformed("wechsel"), height=3, width = 30, font=self.layout["fontSmall"], bg=self.layout["backgroundBtn"], fg=self.layout["fontColor"])
        self.saveBtn = Button(self.topFrame, text="Auswaehlen der Datei", command=lambda: self.controller.actionPerformed("speicherort"), height=3, width = 30, font=self.layout["fontSmall"], bg=self.layout["backgroundBtn"], fg=self.layout["fontColor"])
        #self.setBtn = Button(self.topFrame, text="Auswaehlen der Datei", command=lambda: self.controller.actionPerformed("setFile"), height=2, width = 25, font=self.layout["fontSmall"], bg=self.layout["backgroundBtn"], fg=self.layout["fontColor"])
        self.toplabel = Label(self.topFrame, text="visuelles BCI", font=self.layout["font"], bg=self.layout["backgroundBar"], fg=self.layout["fontColor"], )

        self.topFrame.grid(column=0, row=0)
        self.topFrame.grid_propagate(0)
        self.topFrame.pack_propagate(0)

        self.changeBtn.grid(column=0, row=0, padx=10,pady=5)
        self.saveBtn.grid(column=1, row=0, padx=10, pady=5)
        #self.setBtn.grid(column=2, row=0, padx=10, pady=5)
        self.toplabel.grid(column=2, row=0, padx=100, pady=2)

    def createMainFrame(self):
        '''--------------------------------------------------------------------------------------------------
        Erstellt und postioniert einen Container als Platzhalter fuer die verschiedenen Seiten. Anscliessend
        erstellt es die verschiedenen Seiten und speicher diese in eine Liste
        '''
        self.mainFrame = Frame(self, bg=self.layout["background"], height=250, width=500)
        self.mainFrame.grid(column=0, row=1)
        self.mainFrame.pack_propagate(0)
        
        self.container = Frame(self.mainFrame, bg=self.layout["background"], height=250, width=500)
        self.container.pack(side="top", fill="both", expand = True)
        self.container.pack_propagate(0)
        self.container.grid_propagate(0)
        
        self.frames = {}
        for F in (StartPage, WorkingPageTaktil, WorkingPageVisuell):
            page_name = F.__name__
            frame = F(parent=self.container, controller=self.controller, layout=self.layout)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        
        self.changeFrame("StartPage")
          
    def createBottomFrame(self):
        '''--------------------------------------------------------------------------------------------------
        Erstellt und positioniert ein Label fuer die ganzen Informationen
        '''
        self.bottomFrame = Frame(self, bg=self.layout["backgroundBar"], height=100, width=500)
        self.bottomlabel = Label(self.bottomFrame, text="Hier stehen Infos\nGanz viele", justify='left', font=self.layout["fontInfo"], bg=self.layout["backgroundBar"], fg=self.layout["fontColor"])

        self.bottomFrame.grid(column=0, row=2)
        self.bottomFrame.pack_propagate(0)
        self.bottomFrame.grid_propagate(0)

        self.bottomlabel.grid(padx=5,pady=5)  

    def setInfoText(self, text):
        self.bottomlabel['text'] = text

    def setTitleText(self,text):
        self.title(text)
        self.toplabel["text"] = text

    def setChangeBtnText(self,text):
        self.changeBtn["text"] = text

    def setDefaultPath(self, path):
        self.PATH_DEFAULT = path

    def openfiledialog(self):
        path = self.PATH_DEFAULT
        #file = fd.askopenfilename(initialdir=path)  
        file = fd.askdirectory(initialdir=path)   
        return file

    def savefiledialog(self):
        self.dialog = Tk()

        self.dialog.title("Visuelles Buchstabieren")
        h = 100
        w = 400
        self.dialog.geometry('{}x{}'.format(w,h))
        self.dialog.geometry("+{}+{}".format(100,200))
        l = Label(self.dialog, text="Bitte geben Sie einen Speichernamen ein:")
        eingabefeld = Entry(self.dialog)
        okBtn = Button(self.dialog, text="OK", command=lambda:self.okBtn(eingabefeld.get()))
        l.pack()
        eingabefeld.pack()
        okBtn.pack()

        self.dialog.protocol("WM_DELETE_WINDOW", self.closeDialog)
        self.dialog.mainloop()

    def okBtn(self, text):
        path = self.PATH_DEFAULT + "/" + text
        print(path)
        self.controller.copyspelling(path)
        self.dialog.destroy()

    def closeDialog(self):
        self.controller.copyspelling("-1")
        self.dialog.destroy()
    
    def getWindowSize(self):
        return [self.winfo_x(), self.winfo_y(), self.winfo_height(), self.winfo_width()]


class StartPage(Frame):
    '''--------------------------------------------------------------------------------------------------
    Bildet die Seite in der die Aktionen ausgesucht werden koennen. Beihaltet 2 Buttons einen zum starten
    des freien Buchstabierens und einen yum starten des gefuerten Buchstabierens
    '''
    def __init__(self, parent, controller, layout):
        self.layout = layout

        Frame.__init__(self, parent, height=250, width=500, bg=self.layout["background"])
        self.grid_propagate(0)
        self.pack_propagate(0)
        self.controller = controller

        self.container = Frame(self, bg=self.layout["background"], height=250, width=500)
        self.btnFrame = Frame(self.container, bg=self.layout["background"], height=250, width=250)

        self.container.columnconfigure(0, weight=1)   # Set weight to row and 
        self.container.rowconfigure(0, weight=1)      # column where the widget is
        self.container.grid_propagate(0)
        self.container.pack_propagate(0)

        self.container.pack()
        self.btnFrame.grid()

        testBtn = Button(self.btnFrame, text="gefuehrtes Buchstabieren", command=lambda: self.controller.actionPerformed("copySpelling"), height=6, width = 20, font=self.layout["font"], bg=self.layout["backgroundBtn"], fg=self.layout["fontColor"])
        #testBtn = Button(self.btnFrame, text="copySpelling", command=lambda: self.controller.actionPerformed("test"), height=6, width = 20, font=self.layout["font"], bg=self.layout["backgroundBtn"], fg=self.layout["fontColor"])
        testBtn.grid(row=0,column=0, padx=25,pady=25)

        freeSpellingBtn = Button(self.btnFrame, text="freies Buchstabieren", command=lambda: self.controller.actionPerformed("freeSpelling"), height=6, width = 20, font=self.layout["font"], bg=self.layout["backgroundBtn"], fg=self.layout["fontColor"])
        freeSpellingBtn.grid(row=0, column=1, padx=25,pady=25)

    def adjustSize(self, height, width):
        self.container.configure(height=height, width= width)
        self.btnFrame.configure(height=(height*4)/5, width= width/2)

class WorkingPageTaktil(Frame):
    '''--------------------------------------------------------------------------------------------------
    Bildet die Seite nach Auswahl einer Aktion. Beihaltet einen mittig plazierten Buttons zum stoppen 
    des ablaufenden Vorgang
    '''
    def __init__(self, parent, controller, layout):
        self.layout = layout

        Frame.__init__(self, parent, height=250, width=500, bg=self.layout["background"])
        self.controller = controller


        self.columnconfigure(0, weight=1)   # Set weight to row and 
        self.rowconfigure(0, weight=1)      # column where the widget is

        stopBtn = Button(self, text="stop", command=lambda: self.controller.actionPerformed("stop"), height=4, width = 15, font=self.layout["font"], bg=self.layout["backgroundBtn"], fg=self.layout["fontColor"])
        stopBtn.grid()

    def adjustSize(self, height, width):
        pass

class WorkingPageVisuell(Frame):
    '''--------------------------------------------------------------------------------------------------
    Bildet die Seite nach Auswahl einer Aktion. Beihaltet einen mittig unten plazierten Buttons zum 
    stoppen des ablaufenden Vorgang
    '''
    def __init__(self, parent, controller, layout):
        self.layout = layout

        Frame.__init__(self, parent, height=250, width=500, bg=self.layout["background"])
        self.controller = controller
        self.grid_propagate(0)
        self.pack_propagate(0)

        self.windowFrame = Frame(self, height=200, width=500, bg=self.layout["background"])
        self.windowFrame.grid(column=0, row=0)

        self.buttonFrame = Frame(self, height=200, width=500, bg=self.layout["background"])
        self.buttonFrame.grid(column=0, row=1)
        self.buttonFrame.columnconfigure(0, weight=1)   # Set weight to row and 
        self.buttonFrame.rowconfigure(0, weight=1)      # column where the widget is

        stopBtn = Button(self.buttonFrame, text="stop", command=lambda: self.controller.actionPerformed("stop"), height=1, width = 15, font=self.layout["font"], bg=self.layout["backgroundBtn"], fg=self.layout["fontColor"])
        stopBtn.grid()

    def adjustSize(self, height, width):
        self.windowFrame.configure(height=(height*4)/5, width= width)
        self.buttonFrame.configure(height=(height)/10, width= width)