'''--------------------------------------------------------------------------------------------------
Das Model steuert stellt die Modi unabhaengigen Funktionen bereit
'''

from subprocess import *
from threading import Thread
import time

class Modell(Thread):

    def __init__(self,c, dll):
        Thread.__init__(self)
        self.controller  = c
        self.dll = dll
        self.aktiv= True
    
    def setFunktion(self, func, args=None, kwargs=None):
        pass
        
    def startCopySpelling(self):
        pass
    
    def trainXDawn(self):
        pass

    def trainClassifier(self):
        pass

    def freeSpelling(self):
        pass

    def stop(self):
        '''--------------------------------------------------------------------------------------------------
        Die Funktion stop stopt den ablaufenden Thread
        '''
        print("stop thread")
        self.aktiv = False

    def run(self): 
        '''--------------------------------------------------------------------------------------------------
        Wird bei Thread.start() aus dem Controller aufgerufen und laeuft ab sobald der Thread destartet wurde
        '''
        print("start thread")
        #self.aktiv = True
        t = Thread(target=self.startAquisitionServer)
        t.setDaemon(True)
        t.start()
        
        while self.aktiv:
            time.sleep(0.1)

    def killProzessParent(self):
        '''--------------------------------------------------------------------------------------------------
        schliesst OpenVibe-Designer
        '''
        print('Parent start killing')
        pidOV = 0
        items = []

        prozesse = Popen(["ps", "-e"], stdout=PIPE).communicate()[0].strip()
        zeilen = prozesse.split('\n')
        for z in zeilen:
            if(z.find("openvibe-design") != -1):
                z = z.strip()
                items = z.split(' ')
                pidOV = items[0]
        print(pidOV)
        if pidOV is not 0:
            #kill -TERM veranlasst dem Prozess sich selbst zu beenden (nicht erzwungen)
            try:
                Popen(["kill", "-TERM", str(pidOV)], stdout=PIPE).communicate()
            except:
                print("kein killing")


        print("killed openvibe-designer")

    def killAcquisitionServer(self):
        '''--------------------------------------------------------------------------------------------------
        schliesst den Acquisitionserver
        '''

        print('start killing AS')
        pid = 0
        items = []

        prozesse = Popen(["ps", "-e"], stdout=PIPE).communicate()[0].strip()
        zeilen = prozesse.split('\n')
        for z in zeilen:
            if(z.find("openvibe-acquis") != -1):
                z = z.strip()
                items = z.split(' ')
                pid = items[0]
        if pid is not 0:
            #kill -TERM veranlasst dem Prozess sich selbst zu beenden (nicht erzwungen)
            Popen(["kill", "-TERM", str(pid)], stdout=PIPE).communicate()


        print("killed openvibe-acquisitionserver")

    

    def startAquisitionServer(self):
        '''--------------------------------------------------------------------------------------------------
        startet den Acquisitionserver und steuert die Benutzerausgabe
        '''

        print("start Aquisitionserver")
        self.controller.resetInfo()
        self.controller.addInfoText('Aquisitionserver -- Bitte starten sie den Server\n')

        command = self.dll.getCommandStartAquisitionServer().split(" ")
        process = Popen(command, stdout=PIPE, universal_newlines=True)  

        self.openVibeAktiv = True                 
        while True:
            output = process.stdout.readline()
            print(output.strip())
            x1 = output.find("Connection succeeded")
            x2 = output.find("Now acquiring")
            x3 = output.find("Stopping the acquisition")
            x4 = output.find("Disconnecting")
            init = output.find("Loading plugin: Fiddler")
            y = output.find("Error")
            if(x1 != -1):
                self.controller.addInfoText('Aquisitionserver ist verbunden -- Bitte starten Sie den Server\n')
            elif(x2 != -1 ):
                self.controller.resetInfo()
                self.controller.addInfoText("Aquisitionserver gestartet\n")
                self.minimizeWindow("server")
            elif(x3 != -1 ):
                self.controller.addInfoText("AquisitionServer gestoppt -- Bitte starten Sie den Server\n")
                self.positionWindow("server")
            elif(x4 != -1 ):
                self.controller.addInfoText("Verbindung vom Aquisitionserver getrennt!\n")
                self.positionWindow("server")
            elif(init != -1 ):
                time.sleep(1)
                self.positionWindow("server")
            elif(y != -1 ):
                self.controller.addInfoText("Fehler beim Auisitionserver aufgetaucht\n")
            if not self.aktiv:
                print("stop")
                break

    def positionWindow(self, name):
        '''--------------------------------------------------------------------------------------------------
        positioniert das Fenster auf der GUI
        '''
        print("calls positionWindow")
        parameter = self.controller.getWindowSize()
        positionX = int(parameter[0]+ int(parameter[3] * 0.05))
        positionY = int(parameter[1]) + int(parameter[2]*0.08)
        height = int(parameter[2])*0.55
        width = int(parameter[3])*0.9
        windowID = Popen(["xdotool", "search", "--onlyvisible", "--name", name], stdout=PIPE).communicate()[0].strip()
        try:
            print(int(windowID))
            Popen(["xdotool", "windowsize", windowID, str(width), str(height)], stdout=PIPE).communicate()
            Popen(["xdotool", "windowmove", windowID, str(positionX), str(positionY)], stdout=PIPE).communicate()
            Popen(["xdotool", "windowactivate", windowID], stdout=PIPE).communicate()[0].strip()
        except:
            print("no window")
            print(windowID)
            self.controller.addInfoText("Fehler: kein Fenster gefunden!")

    def minimizeWindow(self, name):
        '''--------------------------------------------------------------------------------------------------
        minimiert das Fenster
        '''
        windowID = Popen(["xdotool", "search", "--onlyvisible", "--name", name], stdout=PIPE).communicate()[0].strip()
        try:
            print(int(windowID))
            Popen(["xdotool", "windowminimize", windowID], stdout=PIPE).communicate()
        except:
            print("no window")
            print(windowID)
            self.controller.addInfoText("Fehler: kein Fenster gefunden!")

    
