# -*- coding: latin-1 -*-
import os
import wx
import wx.lib.scrolledpanel as scrolled
import _winreg
#import MySQLdb
from Crypto.Cipher import AES
from Crypto.Cipher import DES3
import StringIO
import pyHook, time,sys,os,xml.dom.minidom,shutil, getopt
from time import localtime
import pythoncom
import types
import threading
import win32con
import win32process
import win32gui
import win32api
#import win32evtlog
import win32api
import win32file
import win32con
#import win32security # To translate NT Sids to account names.
import pyAA
import wmi
from win32com.shell import shell, shellcon
#import MySQLdb
#import win32evtlogutil
#import md5
from Crypto.Hash import MD5
import codecs
import psycopg2
import webbrowser
import psutil
from threading import Thread


class MyTaskBarIcon(wx.TaskBarIcon):
    global line1,line2,line3
    def __init__(self, frame):
        global line1,line2,line3
        wx.TaskBarIcon.__init__(self)

        self.frame = frame
        self.SetIcon(wx.Icon('img/icone2.png', wx.BITMAP_TYPE_PNG), 'chronos monitor')
        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=1)
        self.Bind(wx.EVT_MENU, self.OnTaskBarDeactivate, id=2)
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=3)
        self.Bind(wx.EVT_MENU, self.OnHelp, id=4)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=5)
 
    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(1, 'Afficher')
        menu.Append(2, 'Cacher')
        menu.Append(3, 'Fermer')
        menu.Append(4, 'Aide')
        menu.Append(5, 'A Propos')
        return menu

    def OnAbout(self,event):
        global line1,line2,line3
        line1="Chronos Monitor Watcher"
        line2="  version 1.00" 
        line3="http://www.chronosmonitor.com"
        try:
            dialogframe = wx.FindWindowById(465)
            dialogframe.Close()
            WizardEnd(None, 465, 'Chronos Monitor Configuration')            
        except:
            WizardEnd(None, 465, 'Chronos Monitor Configuration')

    def OnHelp(self,event):
        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        path="file:///"+oscurdir+"/doc/documentationWatcher.pdf"
        webbrowser.open(path)

    def OnTaskBarClose(self, event):
##        optionsframe = wx.FindWindowById(458)
##        if optionsframe.IsShown():
##            optionsframe.Close()
##        paramframe = wx.FindWindowById(459)
##        if paramframe.IsShown():
##            paramframe.Close()
##        anaframe = wx.FindWindowById(460)
##        if anaframe.IsShown():
##            anaframe.Close()
##        dosframe = wx.FindWindowById(461)
##        if dosframe.IsShown():
##            dosframe.Close()
##        userframe = wx.FindWindowById(462)
##        if userframe.IsShown():
##            userframe.Close()
##        wizardframe = wx.FindWindowById(463)
##        if wizardframe.IsShown():
##            wizardframe.Close()

        for x in range(458,473):
            try:
                frame=wx.FindWindowById(x)
                if frame.IsShown():
                    frame.Close()
            except:
                pass
        self.frame.Close()

    def OnTaskBarActivate(self, event):
        if not self.frame.IsShown():
            self.frame.Show()
        for x in range(458,474):
            try:
                frame=wx.FindWindowById(x)
                if not frame.IsShown():
                    frame.Show()
            except:
                pass
##        optionsframe = wx.FindWindowById(458)
##        if not optionsframe.IsShown():
##            optionsframe.Show()
##        paramframe = wx.FindWindowById(459)
##        if not paramframe.IsShown():
##            paramframe.Show()
##        anaframe = wx.FindWindowById(460)
##        if not anaframe.IsShown():
##            anaframe.Show()
##        dosframe = wx.FindWindowById(461)
##        if not dosframe.IsShown():
##            dosframe.Show()
##        userframe = wx.FindWindowById(462)
##        if not userframe.IsShown():
##            userframe.Show()
##        wizardframe = wx.FindWindowById(463)
##        if not wizardframe.IsShown():
##            wizardframe.Show()


    def OnTaskBarDeactivate(self, event):
        if self.frame.IsShown():
            self.frame.Hide()
        for x in range(458,474):
            try:
                frame=wx.FindWindowById(x)
                if frame.IsShown():
                    frame.Hide()
            except:
                pass
##    optionsframe = wx.FindWindowById(458)
##    if optionsframe.IsShown():
##        optionsframe.Hide()
##    paramframe = wx.FindWindowById(459)
##    if paramframe.IsShown():
##        paramframe.Hide()
##    anaframe = wx.FindWindowById(460)
##    if anaframe.IsShown():
##        anaframe.Hide()
##    dosframe = wx.FindWindowById(461)
##    if dosframe.IsShown():
##        dosframe.Hide()
##    userframe = wx.FindWindowById(462)
##    if userframe.IsShown():
##        userframe.Hide()
##    wizardframe = wx.FindWindowById(463)
##    if wizardframe.IsShown():
##        wizardframe.Hide()
class WizardEnd(wx.Frame):
    global enter,line1,line2,line3,keyvalue,postes,users,deltatrsp
    def __init__(self, parent, id, title):
        global line1,line2,line3,keyvalue,postes,users,deltatrsp
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/info-normal.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        
        self.bitmap = wx.Bitmap('img/info-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/info-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/info-appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/info-rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/info-close.png', wx.BITMAP_TYPE_PNG)


        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        #self.SetTransparent(220)
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)
        
        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(60, 98)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(192, 7)
      
        self.wdc = wx.ClientDC(self)
        self.wdc.DrawBitmap(self.bitmap, 0, 0, True)

        self.Show(True)
        self.Fit()
        self.Centre()
        enter=False
        self.OnDraw()

    def SetNoteShape(self, *event):
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)




    def Draw(self):
        global line1,line2,line3
        self.wdc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.wdc.SetTextBackground(wx.NullColour)
        self.wdc.SetTextForeground('#FFFFFF')
        self.wdc.SetFont(self.wdc.font1)
        self.wdc.DrawText(line1,10,40)
        self.wdc.DrawText(line2,10,55)
        self.wdc.DrawText(line3,10,70)
        self.Show ( True )

    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        self.Draw()
        event.Skip()



    def OnDraw(self):
        
        self.Draw()



    def OnLeftDown(self, event):
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.wizarda)
            if line1=="Licence périmée.":
                try:
                    wizardframe = wx.FindWindowById(463)
                    if wizardframe.IsShown():
                        wizardframe.Show()
                        self.Close()
                except:
                    WizardActivation(None, 463, 'Chronos Monitor Wizard')
                    self.Close()
            else:
                self.Close()          
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                self.Draw()
                enter=True
            elif self.wizardRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                self.Draw()
                enter=True
            else:
                if enter==True:
                    wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                    self.Draw()
                    enter=False
        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        event.Skip()

class UnInstall(wx.Frame):
    global enter,line1,line2,line3,keyvalue,poste,users,deltatrsp
    def __init__(self, parent, id, title):
        global line1,line2,line3,keyvalue,poste,users,deltatrsp
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/info-normal.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        
        self.bitmap = wx.Bitmap('img/question-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/question-normal.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/question-close.png', wx.BITMAP_TYPE_PNG)


        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        #self.SetTransparent(220)
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)
        

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(192, 7)
      
        self.wdc = wx.ClientDC(self)
        self.wdc.DrawBitmap(self.bitmap, 0, 0, True)

        self.Show(True)
        self.Fit()
        self.Centre()
        enter=False
        self.OnDraw()

    def SetNoteShape(self, *event):
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)

    def desinstalle(self,event):
        global poste,line1,line2,line3
        try:
            conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
            conn = psycopg2.connect(conn_string)
            curs = conn.cursor()               
            intostr="""UPDATE postes SET guid='', activated='0' WHERE id='"""+str(poste["PID"])+"""';"""
            result=curs.execute(intostr)
            conn.commit()
            curs.close()
            conn.close()
            path=os.curdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            os.remove(path)
            self.Close()
            line1="Poste désinstallé"
            line2=""
            line3=""
            WizardEnd(None, 469, 'Chronos Monitor')
        except:
            line1="Erreur lors de la desinstallation"
            line2=""
            line3=""
            WizardEnd(None, 469, 'Chronos Monitor')            

    def annulle(self,event):
        self.Destroy()


    def Draw(self):
        global line1,line2,line3
        self.wdc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.wdc.SetTextBackground(wx.NullColour)
        self.wdc.SetTextForeground('#FFFFFF')
        self.wdc.SetFont(self.wdc.font1)
        self.wdc.DrawText(line1,40,40)
        self.wdc.DrawText(line2,40,55)
        self.wdc.DrawText(line3,40,70)
        self.wdc.oui.Show ( True )
        self.wdc.non.Show ( True )
        self.Show ( True )

    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        self.Draw()
        event.Skip()




    def OnDraw(self):
        self.wdc.oui = wx.Button ( self, -1, 'Oui',pos=(20,90) )
        self.wdc.oui.Bind(wx.EVT_BUTTON, self.desinstalle )
        self.wdc.non = wx.Button ( self, -1, 'Non',pos=(120,90) )
        self.wdc.non.Bind(wx.EVT_BUTTON, self.annulle )
        self.Draw()       



    def OnLeftDown(self, event):
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
##        elif self.wizardRegion.ContainsPoint(pos):
##            wx.BufferedDC(wx.ClientDC(self),self.wizarda)
##            if line1=="Licence périmée.":
##                try:
##                    wizardframe = wx.FindWindowById(463)
##                    if wizardframe.IsShown():
##                        wizardframe.Show()
##                        self.Close()
##                except:
##                    WizardActivation(None, 463, 'Chronos Monitor Wizard')
##                    self.Close()
##            else:
##                self.Close()          
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                self.Draw()
                enter=True
##            elif self.wizardRegion.ContainsPoint(pos):
##                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
##                self.Draw()
##                enter=True
            else:
                if enter==True:
                    wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                    self.Draw()
                    enter=False
        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        event.Skip()

class WizardSelect(wx.Frame):
    global jak,enter,line1,line2,line3,keyvalue,postes,users,dc,box,paned,ElChaloR,posteid,deltatrsp
    def __init__(self, parent, id, title):
        global jak,line1,line2,line3,keyvalue,postes,users,dc,box,paned,ElChaloR,oscurdir,posteid
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/fond-choix.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/wizard_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap('img/validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/wizard_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/wizard_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
 #       self.closef = wx.Bitmap('img/close-fond2.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/wizard_close.png', wx.BITMAP_TYPE_PNG)
        self.fond1 = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)
        self.fond2 = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(58, 520)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(190, 10)
        jak='2164691737824342'
        posteid=""
      
##        regroot=_winreg.HKEY_LOCAL_MACHINE
##        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
##        value, type=_winreg.QueryValueEx(hKey, "MachineGuid")
##        print value
        
        for x in range(1,int(users['nombre'])+1):
            users["Checked",int(x)]=False
        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.bdc = wx.BufferedDC(self.cdc)
        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.Show(True)
        self.Fit()
        self.Centre()
#        key=""
        self.OnDraw()

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()
    def OnEraseBackground1(self, evt):
        """
        Add a picture to the background
        """
        # yanked from ColourDB.py
        dc = evt.GetDC()
 
##        if not dc:
##            dc = wx.ClientDC(self)
##            rect = self.GetUpdateRegion().GetBox()
##            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("img/haut.png")
        dc.DrawBitmap(bmp, 0, 0)

    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):
        global key
        key=event.GetString()

    def OnRadio(self,event):
        global posteid,postehip
        hipe=event.GetId()
        #print hipe
        p=0
        hip=""
        for char in str(hipe):
            if p >2:
                hip=hip+char
            p+=1
        #print hip
        posteid=postes["ID",int(hip)]
        postehip=int(hip)
        #print posteid
        
    def OnCheck(self,event):
        global uzerid,panelp,box
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p >2:
                hip=hip+char
            p+=1
        #print hip
       # if self.dc.box[int(hip)].GetValue():
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            users["Checked",int(hip)]=True
            #print 'oui'
        else:
            users["Checked",int(hip)]=False
            #print 'non'
        #print uzer




    def OnApply(self,event):
        global posteid
        for x in range(1,int(users['nombre'])+1):
            #print self.dc.box[x].GetValue()
            pass
    def DShow(self):
        self.dc.DrawText("Veuillez choisir votre poste :",10,30)
        self.dc.DrawText("Veuillez choisir les utilisateurs du poste :",10,280)

    def Draw(self):
        global postes,users,dc,box,panelp,posteid,postehip
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('BLACK')
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##        self.dc.DrawBitmap(self.close, 200, 12, True)
##        self.dc.DrawBitmap(self.wizard, 60, 520, True)
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('BLACK')
        self.dc.SetFont(self.dc.font1)
        #self.dc.SetTextSize(8)
        self.dc.DrawText("Veuillez choisir votre poste :",10,30)
#        self.dc.panel=WizardPanelPostes(self.dc,postes)
        self.dc.panel=scrolled.ScrolledPanel(self,-1,(10,50),(200,200), style=wx.SUNKEN_BORDER)
##        self.dc.panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground1)
        self.dc.panel.SetBackgroundColour('#EAEAE9')
        self.dc.panel.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.DrawBitmap(self.fond1, 10, 60, True)
        #self.dc.panel=MyScrollPanel(self.dc)
        self.dc.postbox=wx.BoxSizer(wx.VERTICAL)
        self.dc.radio={}
        for x in range(1,int(postes['nombre'])+1):
            posy=(int(x)*20)
            idx=4000+int(x)
            self.dc.radio[x]=wx.RadioButton(self.dc.panel,idx,label=str(postes['posteNAME',int(x)]))
            self.dc.postbox.Add(self.dc.radio[x],wx.LEFT)
            self.dc.radio[x].Bind(wx.EVT_RADIOBUTTON, self.OnRadio)
            if int(postes['selected'])==int(x):
                self.dc.radio[x].SetValue(True)
                posteid=postes['ID',x]
                postehip=x
            if posteid=="":
                posteid=idx
                postehip=postes['nombre']
        self.dc.panel.SetSizer(self.dc.postbox)
        self.dc.postbox.FitInside(self.dc.panel)
        #self.dc.postbox.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground1)
#============================================================
        self.dc.DrawText("Veuillez choisir les utilisateurs du poste :",10,280)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,300),(200,200), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond2, 10, 300, True)
        #self.dc.panel=MyScrollPanel(self.dc)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        self.dc.box={}
        for x in range(1,int(users['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=1000+int(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,idx,label=str(users['nom',int(x)])+' '+str(users['prenom',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnCheck)
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)

    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        self.DShow()
        

#============================================================        
        #self.dc.nkey.CanPaste()
        #self.dc.nkey.SetEditable(True)
        #self.dc.nkey.SetValue("CLEF DACTIVATION")
##        self.dc.nkey.Bind(wx.EVT_TEXT, self.OnKey)
##        self.dc.DrawText(str(line1),10,90)
##        self.dc.DrawText(str(line2),10,105)
##        self.dc.DrawText(str(line3),10,120)##        self.dc.DrawBitmap(self.users, 22, 80, True)
##        self.dc.DrawBitmap(self.dossiers, 22, 120, True)
##        self.dc.DrawBitmap(self.analyse, 22, 160, True)
        #self.dc.DrawBitmap(self.reduce, 180, 45, True)
        #self.sync.Bind(wx.EVT_ENTER,self.OnSync)
        #MyButton(self.dc,-1,(51,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        event.Skip()




    def OnDraw(self):
        self.Draw()
        



    def OnLeftDown(self, event):
        global jak,line1,line2,line3,keyvalue,dc,posteid,ElChaloR,posteid,postehip,oscurdir
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            line3=""
            if postes['selected']!=False:
                if postes["ID",int(postes['selected'])]!=posteid:
                    #print 'bingo1'
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()               
                    if postes['selected']!=False:
                        intostr="""UPDATE postes SET guid='', activated='0' WHERE id='"""+str(postes["ID",int(postes['selected'])])+"""';"""

                        result=curs.execute(intostr)
                        conn.commit()
                        #print 'bingo3'
                        

                    intostr="""UPDATE postes SET guid='"""+str(keyvalue)+"""', activated='1' WHERE id='"""+str(posteid)+"""';"""
                            
                    result=curs.execute(intostr)
                    conn.commit()
                    curs.close()
                    conn.close()
            else:
                    #print 'bingo2-'+str(posteid)
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    intostr="""UPDATE postes SET guid='"""+str(keyvalue)+"""', activated='1' WHERE id='"""+str(posteid)+"""';"""
                    try:
                        result=curs.execute(intostr)
                        conn.commit()
                    except:
                        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                        #print "Database connection failed!\n ->%s" % (exceptionValue)
                    curs.close()
                    conn.close()
            try:
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
                #fft=open(TchemFSF, mode ='w+')
            except:
                line2='erreur ouverture fichier'
            try:
                pass
            except:
                line2='erreur ouverture string'
##            try:
##                
##            except:
##                line3='erreur obj'
            
            def Gencrypt(output,TchemFSF):
                global jak
                encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                mlogfile = open(TchemFSF, 'wb')
                ret=''
                while True:
                    chunk = output.read(n=chunksize)
                    #print 'chunk='+repr(chunk)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )                
                    ret=ret+chunk
                #print 'ret='+repr(ret)
                djunky=encryptor.encrypt(ret)
                mlogfile.write(djunky)
                mlogfile.close()
            def Twrite(data):
                fft.write(data)
            try:
                strin=postes["PID"]+'\t'+postes["ID",+int(postehip)]+'\t'+postes["posteNAME",+int(postehip)]+'\t'+postes["dateFin",+int(postehip)]+'\t'+str(key)+'\t'+postes["ADMINID"]+'\n'
                for x in range(1,int(users['nombre'])+1):
                    if users["Checked",x]==True:
                        strin=strin+users["ID",x]+'\t'+users["nom",x]+'\t'+users["prenom",x]+'\t'+users["login",x]+'\t'+users["pass",x]+'\n'
            except:
                line2='dic error'
            try:
                output = StringIO.StringIO(strin)
            except:
                line3='string error'
            try:
                Gencrypt(output,TchemFSF)
            except:
                line3=line3+'-erreur encription'
            try:
                line1="votre poste est maintenant configuré"
                line2=""
            except:
                line1="erreur dans la configuration de votre poste"


            self.Close()
            try:
                dialogframe = wx.FindWindowById(465)
                dialogframe.Close()
                WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            except:
                WizardEnd(None, 465, 'Chronos Monitor Configuration')   
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            self.DShow()
            enter=True
        elif self.wizardRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
            wx.BufferedDC(wx.ClientDC(self),self.wizardr)
            self.DShow()
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                self.DShow()
                enter=False
##            self.dc.DrawBitmap(self.wizard, 60, 520, True)            
##        if event.LeftIsDown()==False:
##            pos = event.GetPosition()
##            if self.wizardRegion.ContainsPoint(pos):
##                #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
##                self.dc.DrawBitmap(self.wizardr, 60, 60, True)
##                enter=True
##            else:
##                if enter==True:
##                    self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                    self.dc.DrawBitmap(self.close, 201, 12, True)
##            ##        self.dc.sincro=self.dc.DrawBitmap(self.sync, 51, 168, True)
##                    #self.oversincro=self.dc.DrawBitmap(self.oversync, 51, 168, True)
##                    #self.oversincro.Hide()
##                    self.dc.DrawBitmap(self.wizard, 60, 60, True)
##                    self.dc.font1 = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, 'AgencyFB-Regular')
##                    self.dc.SetTextBackground(wx.NullColour)
##                    self.dc.SetTextForeground('#6C8D91')
##                    self.dc.SetFont(self.dc.font1)
##                    #self.dc.SetTextSize(8)
##                    self.dc.DrawText("Veuillez saisir la clef d'activation :",10,20)
##                    self.dc.nkey.Show()
##                    self.dc.DrawText(str(line1),10,90)
##                    self.dc.DrawText(str(line2),10,105)
##                    self.dc.DrawText(str(line3),10,120)
##                    enter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

class UserSelect(wx.Frame):
    global jak,enter,line1,line2,line3,keyvalue,poste,user,dc,box,paned,ElChaloR,deltatrsp
    def __init__(self, parent, id, title):
        global jak,line1,line2,line3,keyvalue,poste,user,dc,box,paned,ElChaloR,oscurdir,deltatrsp
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/fond-choix.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/wizard_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap('img/validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/wizard_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/wizard_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
 #       self.closef = wx.Bitmap('img/close-fond2.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/wizard_close.png', wx.BITMAP_TYPE_PNG)
        self.fond1 = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)
        self.fond2 = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(58, 520)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(190, 10)
        jak='2164691737824342'
      
##        regroot=_winreg.HKEY_LOCAL_MACHINE
##        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
##        value, type=_winreg.QueryValueEx(hKey, "MachineGuid")
##        print value
        

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.bdc = wx.BufferedDC(self.cdc)
        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.Show(True)
        self.Fit()
        self.Centre()
#        key=""
        
        self.OnDraw()
##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()
    def OnEraseBackground1(self, evt):
        """
        Add a picture to the background
        """
        # yanked from ColourDB.py
        dc = evt.GetDC()
 
##        if not dc:
##            dc = wx.ClientDC(self)
##            rect = self.GetUpdateRegion().GetBox()
##            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("img/haut.png")
        dc.DrawBitmap(bmp, 0, 0)

    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):
        global key
        key=event.GetString()

        
    def OnCheck(self,event):
        global users
        uzer=event.GetId()
        hip=event.GetId()

        
       # if self.dc.box[int(hip)].GetValue():
        tuser = wx.FindWindowById(int(uzer))
        if tuser.GetValue():
            users["Checked",int(hip)]=True
        else:
            users["Checked",int(hip)]=False
            print 'non'
        #print uzer

    def ChargePoste(self):
        global poste,users
        TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
        fft=open(TchemFSF, mode ='rb')
        output = StringIO.StringIO(fft.read())
        decoutput=StringIO.StringIO()
        #output.write(fft.read())
        fft.close()
        def Gdecrypt(output,decoutput):
            global jak
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=output.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            decoutput.write(rep)
            return decoutput

        Gdecrypt(output,decoutput)
        lines={}
        lines = decoutput.getvalue()
        #print 'lines-'+repr(lines)
        #lo=len(lines)
        #lines = decoutput.readlines()
        #print decoutput.getvalue()
        p=0
        poste={}
        user={}
        l=0
        poste["PID"]=""
        poste["ID"]=""
        poste["posteNAME"]=""
        poste["Date"]=""
        poste["GUID"]=""
        poste["ADMINID"]=""
        T=False
        for char in lines:
            if char=='\t':
                p+=1
                continue
            if char=='\n':
                T=True
                p=0
                l+=1
                user["ID",l]=""
                user["nom",l]=""
                user["prenom",l]=""
                user["login",l]=""
                user["pass",l]=""
                user["Checked",l]=False
                continue
            if p==0 and l==0:poste["PID"]=poste["PID"]+char
            if p==1 and l==0:poste["ID"]=poste["ID"]+char
            if p==2 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
            if p==3 and l==0:poste["Date"]=poste["Date"]+char
            if p==4 and l==0:poste["GUID"]=poste["GUID"]+char
            if p==5 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
            if T==True and p==0:user["ID",l]= user["ID",l]+char
            if T==True and p==1:user["nom",l]= user["nom",l]+char
            if T==True and p==2:user["prenom",l]= user["prenom",l]+char
            if T==True and p==3:user["login",l]= user["login",l]+char
            if T==True and p==4:user["pass",l]= user["pass",l]+char
        user["nombre"]=l
        try:
            conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
            conn = psycopg2.connect(conn_string)
            curs = conn.cursor()
            result=curs.execute("SELECT nom,prenom,id,admin,login,pass FROM users WHERE idadmin='"+str(poste["ADMINID"])+"';" )
            result=curs.fetchall()
            u=1
            if result:
                active=True
                users={}
                for chain in result:
                    #print chain
                    users['nom',u]=""
                    users['prenom',u]=""
                    users['ID',u]=""
                    users['admin',u]=""
                    users['pass',u]=""
                    users['login',u]=""
                    users["Checked",u]=False
                    #users['adminID',u]=""
                    p=0
                    for char in chain:
                        #print char
                        if p==0:users['nom',u]=users['nom',u]+str(char)
                        if p==1:users['prenom',u]=users['prenom',u]+str(char)
                        if p==2:users['ID',u]=users['ID',u]+str(char)
                        if p==3:users['admin',u]=users['admin',u]+str(char)
                        if p==4:users['login',u]=users['login',u]+str(char)
                        if p==5:users['pass',u]=users['pass',u]+str(char)
                        p+=1
                    users['nombre']=u
                    u+=1
        except:
            line1="Connection internet indisponible"

    def OnApply(self,event):
        global posteid
        for x in range(1,int(user['nombre'])+1):
            pass
    def DShow(self):
        self.dc.DrawText("Veuillez choisir les utilisateurs du poste :",10,30)

    def Draw(self):
        global poste,users,dc,box,panelp
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.SetFont(self.dc.font1)
        self.dc.DrawText("Veuillez choisir les utilisateurs du poste :",10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,50),(200,300), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond2, 10, 50, True)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        self.dc.box={}
        for x in range(1,int(users['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=int(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,idx,label=str(users['nom',int(x)])+' '+str(users['prenom',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnCheck)
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)

    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
        self.DShow()
        event.Skip()




    def OnDraw(self):
        self.ChargePoste()
        self.Draw()        



    def OnLeftDown(self, event):
        global jak,line1,line2,line3,keyvalue,dc,posteid,ElChaloR,posteid,postehip,oscurdir,poste,users
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            line3=""
            try:
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            except:
                line2='erreur ouverture fichier'
            try:
                pass
            except:
                line2='erreur ouverture string'
##            try:
##                
##            except:
##                line3='erreur obj'
            
            def Gencrypt(output,TchemFSF):
                global jak
                encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                mlogfile = open(TchemFSF, 'wb')
                ret=''
                while True:
                    chunk = output.read(n=chunksize)
                    #print 'chunk='+repr(chunk)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )                
                    ret=ret+chunk
                #print 'ret='+repr(ret)
                djunky=encryptor.encrypt(ret)
                mlogfile.write(djunky)
                mlogfile.close()
            def Twrite(data):
                fft.write(data)
            #try:
            strin=poste["PID"]+'\t'+poste["ID"]+'\t'+poste["posteNAME"]+'\t'+poste["Date"]+'\t'+poste["GUID"]+'\t'+poste["ADMINID"]+'\n'
            for x in range(1,int(users['nombre'])+1):
                if users["Checked",x]==True:
                    strin=strin+users["ID",x]+'\t'+users["nom",x]+'\t'+users["prenom",x]+'\t'+users["login",x]+'\t'+users["pass",x]+'\n'
            #except:
                #line3='dic error'
            try:
                output = StringIO.StringIO(strin)
                #print 'strin='+repr(strin)
            except:
                line3='string error'
            try:
                Gencrypt(output,TchemFSF)
            except:
                line2='erreur encription'
            try:
                line1="Les utilisateurs sont maintenant configurés"
                line2=""
            except:
                line1="erreur dans la configuration de votre poste"
                line2=""


            self.Close()
            try:
                dialogframe = wx.FindWindowById(465)
                dialogframe.Close()
                WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            except:
                WizardEnd(None, 465, 'Chronos Monitor Configuration')
   
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            self.DShow()
            enter=True
        elif self.wizardRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.wizardr)
            self.DShow()
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                self.DShow()
                enter=False


        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

           
class WizardActivation(wx.Frame):
    global enter,line1,line2,keyvalue,postes,users,key,deltatrsp
    def __init__(self, parent, id, title):
        global line1,line2,keyvalue,postes,users,key
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/fond-small-wizard.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/code_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap('img/validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/code_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/code_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/code_close.png', wx.BITMAP_TYPE_PNG)


        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Rendez vous sur chronosmonitor.com"
        line2="Pour obtenir une clef d'activation"
        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)
        

        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(60, 100)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(190, 12)
      
        regroot=_winreg.HKEY_LOCAL_MACHINE
        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
        keyvalue, type=_winreg.QueryValueEx(hKey, "MachineGuid")
        #print keyvalue

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.bdc = wx.BufferedDC(self.cdc)
        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.Show(True)
        self.Fit()
        self.Centre()
        key=""
        self.OnDraw()

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):
        global key
        key=event.GetString()

    def Draw(self):
        global line1,line2
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')
        #panel=
        #MyBG(self,-1)
        #panel = MyPanel(self, -1)
        #MyButton(self,-1,(49,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.SetFont(self.dc.font1)
        #self.dc.SetTextSize(8)
        self.dc.DrawText("Veuillez saisir la clef d'activation :",10,23)
        self.dc.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.dc.nkey.CanPaste()
        self.dc.nkey.SetEditable(True)
        #self.dc.nkey.SetValue("CLEF DACTIVATION")
        self.dc.nkey.Bind(wx.EVT_TEXT, self.OnKey)
        self.dc.DrawText(str(line1),10,60)
        self.dc.DrawText(str(line2),10,75)

    def DShow(self):
        global line1,line2
        self.dc.DrawText("Veuillez saisir la clef d'activation :",10,23)
        #self.dc.nkey.Show()
        self.dc.DrawText(str(line1),10,60)
        self.dc.DrawText(str(line2),10,75)
        
    def OnPaint(self, event):
        
        wx.BufferedPaintDC(self,self.bitmap)
        self.DShow()
        
        

##        self.dc.DrawBitmap(self.users, 22, 80, True)
##        self.dc.DrawBitmap(self.dossiers, 22, 120, True)
##        self.dc.DrawBitmap(self.analyse, 22, 160, True)
        #self.dc.DrawBitmap(self.reduce, 180, 45, True)
        #self.sync.Bind(wx.EVT_ENTER,self.OnSync)
        #MyButton(self.dc,-1,(51,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        event.Skip()



    def OnDraw(self):
        self.Draw()
        




    def OnLeftDown(self, event):
        global line1,line2,keyvalue,postes,users,key
##        self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
            #self.dc.DrawBitmap(self.wizarda, 60, 60, True)
            active=False
            if str(key)=="":
                line1=""
                line2="Veuillez introduire un code d'activation"
            else :
                #try:
                if key:
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    result=curs.execute("SELECT nom,prenom,id,admin,login,pass,idadmin FROM users WHERE keycode='"+str(key)+"';" )
                    result=curs.fetchall()
                    u=1
                    postes={}
                    users={}
                    postes['nombre']=0
                    users['nombre']=0
                    if result:
                        active=True
                        for chain in result:
                            #print chain
                            users['nom',u]=""
                            users['prenom',u]=""
                            users['ID',u]=""
                            users['admin',u]=""
                            users['pass',u]=""
                            users['login',u]=""
                            postes['ADMINID']=""
                            users['nombre']=u
                            #users['adminID',u]=""
                            p=0
                            for char in chain:
                                #print char
                                if p==0:users['nom',u]=users['nom',u]+str(char)
                                if p==1:users['prenom',u]=users['prenom',u]+str(char)
                                if p==2:users['ID',u]=users['ID',u]+str(char)
                                if p==3:users['admin',u]=users['admin',u]+str(char)
                                if p==4:users['login',u]=users['login',u]+str(char)
                                if p==5:users['pass',u]=users['pass',u]+str(char)
                                if p==6:postes['ADMINID']=postes['ADMINID']+str(char)
                                p+=1
                            #print "nombre=",users['nombre']
                            #if pid:postes['ADMINID']=str(pid)
                            u+=1
                    try:
                        u=1
                        #print 'pid='+repr(postes['ADMINID'])
                        query2="SELECT id,postename,datefin,activated,guid FROM postes WHERE userid='"+str(postes['ADMINID'])+"';"
                        #print query2
                        try:
                            presult=curs.execute(query2)
                            presult=curs.fetchall()                                                   
                        except:
                            exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                            print "Database connection failed!\n ->%s" % (exceptionValue)
                            line3="erreur 88" 
                        if presult:
                            #print 'bingo'
                            active=True
                            postes['selected']=False
                            for pchain in presult:
                                #print pchain
                                postes['ID',u]=""
                                postes['posteNAME',u]=""
                                postes['dateFin',u]=""
                                postes['activated',u]=""
                                postes['guid',u]=""
                                postes['nombre']=u
                                p=0
                                for pchar in pchain:
                                    #print pchar
                                    if p==0:postes['ID',u]=postes['ID',u]+str(pchar)
                                    if p==1:postes['posteNAME',u]=postes['posteNAME',u]+str(pchar)
                                    if p==2:postes['dateFin',u]=postes['dateFin',u]+str(pchar)
                                    if p==3:postes['activated',u]=postes['activated',u]+str(pchar)
                                    if p==4:postes['guid',u]=postes['guid',u]+str(pchar)
                                    p+=1
                                if postes['guid',u]==str(keyvalue) and postes['activated',u]=="1":
                                    postes['selected']=u
                                    u+=1
                                elif postes['activated',u]=="0":
                                    u+=1
                                #print 'u=',u,'selected=',postes['selected'],"activated=",
    
                    except:
                        line2=str(line2)+"2"
                    if active==True:
                        postes['PID']=postes['ADMINID']
                        self.Close()
                        try:
                            dialogframe = wx.FindWindowById(467)
                            dialogframe.Close()
                            WizardSelect(None, 467, 'Chronos Monitor')            
                        except:
                            WizardSelect(None, 467, 'Chronos Monitor')
                        
                    else:
                        line1=""
                        line2="code incorrect"

                    curs.close()
                    conn.close()
##                except:
##                    line2=str(line2)+"2"                   

            
##            self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##            self.dc.DrawBitmap(self.close, 201, 12, True)
##            self.dc.DrawBitmap(self.wizarda, 60, 60, True)
            wx.BufferedDC(wx.ClientDC(self),self.wizarda)
            self.DShow()
##            self.dc.font1 = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL,False, 'AgencyFB-Regular')
##            self.dc.SetTextBackground(wx.NullColour)
##            self.dc.SetTextForeground('#6C8D91')
##            self.dc.SetFont(self.dc.font1)
##            #self.dc.SetTextSize(8)
##            self.dc.DrawText("Veuillez saisir la clef d'activation :",10,20)
##            self.dc.nkey.Show()
##            self.dc.DrawText(str(line1),10,90)
##            self.dc.DrawText(str(line2),10,105)
##            self.dc.DrawText(str(line3),10,120)            
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                self.DShow()
                enter=True
            elif self.wizardRegion.ContainsPoint(pos):
                #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                self.DShow()
##                self.dc.DrawBitmap(self.wizardr, 60, 60, True)
                enter=True
            else:
                if enter==True:
                    wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                    self.DShow()
##                    self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                    self.dc.DrawBitmap(self.close, 201, 12, True)
##            ##        self.dc.sincro=self.dc.DrawBitmap(self.sync, 51, 168, True)
##                    #self.oversincro=self.dc.DrawBitmap(self.oversync, 51, 168, True)
##                    #self.oversincro.Hide()
##                    self.dc.DrawBitmap(self.wizard, 60, 60, True)
##                    self.dc.font1 = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, 'AgencyFB-Regular')
##                    self.dc.SetTextBackground(wx.NullColour)
##                    self.dc.SetTextForeground('#6C8D91')
##                    self.dc.SetFont(self.dc.font1)
##                    #self.dc.SetTextSize(8)
##                    self.dc.DrawText("Veuillez saisir la clef d'activation :",10,20)
##                    self.dc.nkey.Show()
##                    self.dc.DrawText(str(line1),10,90)
##                    self.dc.DrawText(str(line2),10,105)
##                    self.dc.DrawText(str(line3),10,120)
                    enter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()
        
class PassExport(wx.Frame):
    global enter,line1,line2,key,dusers,deltatrsp
    def __init__(self, parent, id, title):
        global line1,line2,key,dusers
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/fond-small-wizard.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/code_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        #self.wizardf = wx.Bitmap('img/validerf.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/code_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/code_rollover.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/code_close.png', wx.BITMAP_TYPE_PNG)

        key=""

        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Veuillez entrer votre code export"
        line2="Demandez à votre administrateur"
        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.closeRegion = wx.RegionFromBitmap(self.close)
        

        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(60, 100)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(190, 12)
      
        regroot=_winreg.HKEY_LOCAL_MACHINE
        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
        keyvalue, type=_winreg.QueryValueEx(hKey, "MachineGuid")
        #print keyvalue

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        #self.bdc = wx.BufferedDC(self.cdc)
        #self.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.Show(True)
        self.Fit()
        self.Centre()
        key=""
        self.OnDraw()

##    def OnClose(self, event):
##        self.tskic.Destroy()
##        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):
        global key
        key=event.GetString()

    def Draw(self):
        global line1,line2
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')
        #panel=
        #MyBG(self,-1)
        #panel = MyPanel(self, -1)
        #MyButton(self,-1,(49,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.SetFont(self.dc.font1)
        #self.dc.SetTextSize(8)
        self.dc.DrawText("Veuillez saisir le code export :",10,23)
        self.dc.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.dc.nkey.CanPaste()
        self.dc.nkey.SetEditable(True)
        #self.dc.nkey.SetValue("CLEF DACTIVATION")
        self.dc.nkey.Bind(wx.EVT_TEXT, self.OnKey)
        self.dc.DrawText(str(line1),10,60)
        self.dc.DrawText(str(line2),10,75)

    def DShow(self):
        global line1,line2
        self.dc.DrawText("Veuillez saisir le code export :",10,23)
        self.dc.nkey.Show()
        self.dc.DrawText(str(line1),10,60)
        self.dc.DrawText(str(line2),10,75)
        
    def OnPaint(self, event):
        
        wx.BufferedPaintDC(self,self.bitmap)
        self.DShow()
        

##        self.dc.DrawBitmap(self.users, 22, 80, True)
##        self.dc.DrawBitmap(self.dossiers, 22, 120, True)
##        self.dc.DrawBitmap(self.analyse, 22, 160, True)
        #self.dc.DrawBitmap(self.reduce, 180, 45, True)
        #self.sync.Bind(wx.EVT_ENTER,self.OnSync)
        #MyButton(self.dc,-1,(51,168),'img/sync-normal2.png','img/sync-rollover2.png','img/appui-sync2.png')
        event.Skip()




    def OnDraw(self):
        self.Draw()



    def OnLeftDown(self, event):
        global line1,line2,key,dusers
##        self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
            #self.dc.DrawBitmap(self.wizarda, 60, 60, True)
            active=False
            if key=="":
                line1=""
                line2="Veuillez introduire un code"
            else :
                #try:
                if key:
                    if dusers['password']==key:
                        try:
                            exportframe = wx.FindWindowById(470)
                            if exportframe.IsShown():
                                exportframe.Show()
                                self.Close()
                        except:
                            Export(None, 470, 'Chronos Monitor')
                            self.Close()
                    else:
                        line1=""
                        line2="code incorrect"

            wx.BufferedDC(wx.ClientDC(self),self.wizarda)
            self.DShow()           
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                self.DShow()
                enter=True
            elif self.wizardRegion.ContainsPoint(pos):
                #self.dc.DrawBitmap(self.wizardf, 22, 40, True)
                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                self.DShow()
##                self.dc.DrawBitmap(self.wizardr, 60, 60, True)
                enter=True
            else:
                if enter==True:
                    wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                    self.DShow()
                    enter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

class Parametres(wx.Frame):
    global dusers,reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,ssyncro,analyse,question,deltatrsp
    def __init__(self, parent, id, title):
        global dusers,reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,ssyncro,analyse,question,deltatrsp
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/parametres_0.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/parametres_0.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/parametres_close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap('img/parametres_app.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap('img/parametres_rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        

        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

 
        enter=False         
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.validRegion = wx.RegionFromBitmap(self.valid)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.validRegion.IntersectRegion(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
        jak='2164691737824342'

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        self.Centre()

        self.OnDraw()

    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):

        pass

    def OnRadio(self,event):
        pass
        

    def chargeConfig(self):
        global deltatrsp,oscurdir,jak,ElChaloR,ssyncro,analyse,question,dinac,dtp,dina
        def Gdecrypt(output,decoutput):
            global jak,ElChaloR
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=output.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            decoutput.write(rep)
            return decoutput
        glorb=False
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'config.gwh'
            fft=open(TchemFSF, mode ='rb')
            output = StringIO.StringIO(fft.read())
            decoutput=StringIO.StringIO()
            fft.close()
            Gdecrypt(output,decoutput)
            lines={}
            p=0
            lines = decoutput.getvalue()
            tsyncro=""
            tanalyse=""
            tquestion=""
            tdeltatrsp=""
            tdinac=""
            for char in lines:
                if char=='\t':
                    p+=1
                    continue
                if char=='\n':
                    glorb=True
                    break
                if p==0:
                    tsyncro=tsyncro+char
                if p==1:
                    tanalyse=tanalyse+char
                if p==2:
                    tquestion=tquestion+char
                if p==3:
                    tdeltatrsp=tdeltatrsp+char
                if p==4:
                    tdinac=tdinac+char

            decoutput.close()
            output.close()
            if glorb==True:
                if tsyncro=="True":ssyncro=True
                else:ssyncro=False
                if tanalyse=="True":analyse=True
                else:analyse=False
                if tquestion=="True":question=True
                else:question=False
                deltatrsp=tdeltatrsp
                dtp=tdeltatrsp
                dinac=tdinac
                dina=dinac
                self.SetTransparent(int(deltatrsp))
                self.Show(True)
        except:
            question=False
            analyse=False
            ssyncro=False
            deltatrsp=255
            dinac=60
            dtp=deltatrsp
            dina=dinac



    def OnApply(self,event):
        pass
    
    def Export(self,event):
        global dusers
        if dusers['export']=="1":
            try:
                exportframe = wx.FindWindowById(470)
                if exportframe.IsShown():
                    exportframe.Show()
            except:Export(None, 470, 'Chronos Monitor')
        elif dusers['export']=="m":
            try:
                pexportframe = wx.FindWindowById(471)
                if pexportframe.IsShown():
                    pexportframe.Show()
            except:PassExport(None, 471, 'Chronos Monitor')

    def desinstalle(self,event):
        global dusers,line1,line2,line3
        if dusers['config']=="1":
            try:
                uninstallframe = wx.FindWindowById(473)
                if uninstallframe.IsShown():
                    uninstallframe.Show()
            except:
                line1="Etes vous sûr de vouloir"
                line2="desinstaller votre poste?"
                line3=""
                UnInstall(None, 473, 'Chronos Monitor')

            

    def OnTTexT(self,event):
        global dtp
        dtp=event.GetString()

    def OnDTexT(self,event):
        global dina
        dina=event.GetString()

    def OnSyncroCheck(self,event):
        global ssyncro
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p ==4:
                hip=hip+char
            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            ssyncro=True
        else:
            ssyncro=False


    def OnAnalyseCheck(self,event):
        global analyse
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p ==4:
                hip=hip+char
            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            analyse=True
        else:
            analyse=False


    def OnQuestionCheck(self,event):
        global question
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p ==4:
                hip=hip+char
            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            question=True
        else:
            question=False
       
    
    def Draw(self):
        global ssyncro,analyse,question,deltatrsp,dinac
        self.dc.SetFont(self.font)
        self.dc.font1 = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, 'AgencyFB-Regular')
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#FFFFFF')
        self.dc.SetFont(self.dc.font1)
        self.dc.panel = wx.Panel ( self,-1,(10,50),(150,200), style=wx.SUNKEN_BORDER)
        self.dc.sizer = wx.GridBagSizer ( 7, 5 )
        self.dc.panel.SetBackgroundColour("#D5D5D5")
        if dusers['config']=="1":
            self.dc.boxdossiers=wx.CheckBox(self.dc.panel,30001,label='supervision des dossiers')
            self.dc.boxdossiers.Bind(wx.EVT_CHECKBOX, self.OnSyncroCheck)
            self.dc.boxdossiers.SetValue(ssyncro)
            self.dc.boxanalyse=wx.CheckBox(self.dc.panel,30002,label='analyse automatique à la synchronisation')
            self.dc.boxanalyse.Bind(wx.EVT_CHECKBOX, self.OnAnalyseCheck)
            self.dc.boxanalyse.SetValue(analyse)
            self.dc.boxquestion=wx.CheckBox(self.dc.panel,30003,label='question après inactivité')
            self.dc.boxquestion.Bind(wx.EVT_CHECKBOX, self.OnQuestionCheck)
            self.dc.boxquestion.SetValue(question)
            self.dc.transparence=wx.TextCtrl(self.dc.panel,wx.ID_ANY,str(deltatrsp),size=(40,21))
            self.dc.transparence.SetEditable(True)
            self.dc.transparence.Bind(wx.EVT_TEXT, self.OnTTexT)
            self.dc.transparencetxt = wx.StaticText(self.dc.panel, -1, 'Degré de transparence des fenêtres (0:transparent à 255:opaque)')
            self.dc.delai=wx.TextCtrl(self.dc.panel,wx.ID_ANY,str(dinac),size=(40,21))
            self.dc.delai.SetEditable(True)
            self.dc.delai.Bind(wx.EVT_TEXT, self.OnDTexT)
            self.dc.delaitxt = wx.StaticText(self.dc.panel, -1, "délai d'inactivité (en secondes)")
            self.dc.message = wx.StaticText(self.dc.panel, -1, '')
            self.dc.uninstall = wx.Button ( self.dc.panel, 100, 'Desinstaller' )
            self.dc.uninstall.Bind(wx.EVT_BUTTON, self.desinstalle )
        if dusers['export']=="1" or dusers['export']=="m":
            self.dc.export = wx.Button ( self.dc.panel, 100, 'Export' )
            self.dc.export.Bind(wx.EVT_BUTTON, self.Export )
        if dusers['config']=="1":
            self.dc.sizer.Add ( self.dc.boxdossiers, ( 1, 0 ) )
            self.dc.sizer.Add ( self.dc.boxanalyse, ( 2, 0 ) )
            self.dc.sizer.Add ( self.dc.boxquestion, ( 3, 0 ) )
            self.dc.sizer.Add ( self.dc.transparence, ( 4, 1 ) )
            self.dc.sizer.Add ( self.dc.transparencetxt, ( 4, 0 ) )
            self.dc.sizer.Add ( self.dc.delai, ( 5, 1 ) )
            self.dc.sizer.Add ( self.dc.delaitxt, ( 5, 0 ) )
            self.dc.sizer.Add ( self.dc.message, ( 6, 0 ) )
            self.dc.sizer.Add ( self.dc.uninstall, ( 7, 1 ) )
        if dusers['export']=="1" or dusers['export']=="m":
            self.dc.sizer.Add ( self.dc.export, ( 7, 0 ) )#, ( 1, 3 ), wx.ALIGN_CENTERs
        self.dc.horizontal = wx.BoxSizer ( wx.HORIZONTAL )
        self.dc.horizontal.Add ( ( 0, 0 ), 1 )
        self.dc.horizontal.Add ( self.dc.sizer )
        self.dc.horizontal.Add ( ( 0, 0 ), 1 )
        self.dc.vertical = wx.BoxSizer ( wx.VERTICAL )
        self.dc.vertical.Add ( ( 0, 0, ), 1 )
        self.dc.vertical.Add ( self.dc.horizontal, 0, wx.ALIGN_CENTER )
        self.dc.vertical.Add ( ( 0, 0 ), 1 )
        self.dc.panel.SetSizerAndFit ( self.dc.vertical )
        self.Show ( True )
        
    def OnPaint(self, event):

        wx.BufferedPaintDC(self,self.bitmap)

        event.Skip()

    def OnDraw(self):
        self.chargeConfig()
        self.Draw()        


    def verifyTransparency(self):
        global vtp,dtp,message
        message=""
        try:
            if (int(dtp)>=0) and (int(dtp)<=255):
                vtp="OK"
                message="Attention le degré 0 rend completement transparent vos fenêtres"
            else:
                vtp="NOT"
                message="Le degré de transparence doit être un nombre compris entre 0 et 255"
        except:
            vtp="NOT"
            message="Le degré de transparence doit être un nombre compris entre 0 et 255"
            

    def verifyDina(self):
        global dina,vtp,message
        try:
            if int(dina)>=0:
                pass
            else:
                vtp="NOT"
                message="Le délai d'inactivité doit être un nombre supérieur à 0"
        except:
            vtp="NOT"
            message="Le délai d'inactivité doit être un nombre supérieur à 0"

    def saveConfig(self):
        global ssyncro,analyse,question,dtp,dina,jak,ElChaloR,oscurdir,message,deltatrsp
        def Gencrypt(output,TchemFSF):
            global jak,ElChaloR
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(TchemFSF, 'wb')
            ret=''
            while True:
                chunk = output.read(n=chunksize)
                #print 'chunk='+repr(chunk)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            #print 'ret='+repr(ret)
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        message="erreur lors de l'enregistrement de la configuration"
        TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'config.gwh'
        strin=str(ssyncro)+'\t'+str(analyse)+'\t'+str(question)+'\t'+str(dtp)+'\t'+str(dina)+'\n'
        output = StringIO.StringIO(strin)
        Gencrypt(output,TchemFSF)
        message=""
        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset,ssyncro,analyse,question,dtp,dina,jak,ElChaloR,oscurdir,message,deltatrsp
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+" Export(None, -1, 'Chronos Monitor')
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
            if dusers['config']=="1":
                def Gencrypt(output,TchemFSF):
                    global jak,ElChaloR
                    encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                    chunksize=(64*1024)
                    mlogfile = open(TchemFSF, 'wb')
                    ret=''
                    while True:
                        chunk = output.read(n=chunksize)
                        #print 'chunk='+repr(chunk)
                        if len(chunk)==0:
                            break
                        elif len(chunk)%16!=0:
                            chunk += ' ' * (16-len(chunk) % 16 )                
                        ret=ret+chunk
                    #print 'ret='+repr(ret)
                    djunky=encryptor.encrypt(ret)
                    mlogfile.write(djunky)
                    mlogfile.close()
                message="erreur lors de l'enregistrement de la configuration"
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'config.gwh'
                strin=str(ssyncro)+'\t'+str(analyse)+'\t'+str(question)+'\t'+str(dtp)+'\t'+str(dina)+'\n'
                output = StringIO.StringIO(strin)
                Gencrypt(output,TchemFSF)
                message=""
                self.verifyTransparency()
                self.verifyDina()
                try:
                    self.saveConfig()
                    try:
                        if str(vtp)=="OK":
                            reset=True
                            line1="Configuration enregistrée."
                            line2="Veuillez relancer le programme"
                            line3="Pour la prendre en compte"
                            self.Close()
                            try:
                                dialogframe = wx.FindWindowById(465)
                                dialogframe.Close()
                                WizardEnd(None, 465, 'Chronos Monitor Parametres')            
                            except:
                                WizardEnd(None, 465, 'Chronos Monitor Parametres')
                            
                        elif str(vtp)=="NOT":
                            self.dc.message.SetLabel(message)
                    except:
                        self.dc.message.SetLabel(message)
                except:
                    self.dc.message.SetLabel(message)
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            enter=True
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.validr)
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                enter=False          

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

class Analyse(wx.Frame):
    global jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtre,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,xlisteclient,xlisteactivite,listetache,deltatrsp
    def __init__(self, parent, id, title,messagem):
        global jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtre,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,xlisteclient,xlisteactivite,listetache,deltatrsp
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/analyse.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/analyse-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/analyse-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap('img/analyse-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap('img/analyse-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap('img/analyse-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        filtre={}
        checkfichier={}
        jak='2164691737824342'
        filtre['nombre']=0
        Tcontenant=""
        Tcontenu=""
        Tpropriete=""
        Tfiltre=""
        Tclient=""
        Tprestation=""
        Ttache=""
        Tprestationid=""
        xlisteclient = ['non défini']
        xlisteactivite = ['non défini']
        message=messagem

        
        

        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Rendez Vous sur :"
        line2="http://www.chronosmonitor.fr"
        line3="Pour obtenir une clef d'activation"  
        enter=False         
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.validRegion = wx.RegionFromBitmap(self.valid)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.validRegion.IntersectRegion(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
      

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        self.Centre()

        self.OnDraw()

    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):

        pass

    def OnRadio(self,event):
        pass
        
    def OnApply(self,event):
        pass
    
    def importexport(self,event):
        try:
            dialogframe = wx.FindWindowById(472)
            dialogframe.Show()           
        except: 
            AnalyseIE(None, 472, 'Chronos Monitor Analyse Import Export','Selectionnez les filtres à importer/exporter')

    def OnTTexT(self,event):
        global dtp
        dtp=event.GetString()

    def OnContSelect(self,event):
        global Tcontenant
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tcontenant=user.GetValue()

    def OnPropSelect(self,event):
        global Tpropriete
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tpropriete=user.GetValue()

    def OnContenuSelect(self,event):
        global Tcontenu
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tcontenu=user.GetValue()

    def OnFiltreSelect(self,event):
        global Tfiltre
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tfiltre=user.GetValue()

    def OnClientSelect(self,event):
        global Tclient
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tclient=user.GetValue()

    def OnPrestaSelect(self,event):
        global Tprestation,presta,Tprestationid
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tprestation=user.GetValue()
        ft=len(Tprestation)
        if int(ft)>10 and Tprestation[0:10]=='  --  --  ':
            for x in range(1,presta['1','count']+1):
                for t in range(1,presta['2','count']+1):
                    for r in range(1,presta['3','count']+1):
                        try:
                            if presta[x,t,r,'label']==Tprestation:
                                Tprestationid=presta[x,t,r,'id']
                        except:
                            pass
        elif int(ft)>6 and Tprestation[0:6]=='  --  ':                
            for x in range(1,presta['1','count']+1):
                for t in range(1,presta['2','count']+1):
                    try:
                        if presta[x,t,'0','label']==Tprestation:
                            Tprestationid=presta[x,t,'0','id']
                    except:
                        pass
        else:                
            for x in range(1,presta['1','count']+1):
                try:
                    if presta[x,'0','0','label']==Tprestation:
                        Tprestationid=presta[x,'0','0','id']
                except:
                    pass
    def OnTacheSelect(self,event):
        global Ttache
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Ttache=user.GetValue()


    def OnFiltreCheck(self,event):
        global filtre
        uzer=event.GetId()
##        p=0
        hip=uzer
##        for char in str(uzer):
##            if p >2:
##                hip=hip+char
##            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            filtre["checked",int(hip)]=True
        else:
            filtre["checked",int(hip)]=False

        self.dc.contenanttxt.SetLabel(filtre["Libelle",int(hip)] + ": Si "+filtre["Contenant",int(hip)] )
        self.dc.contenutxt.SetLabel(filtre["Propriete",int(hip)] + ' "'+  filtre["Contenu",int(hip)]+'"' )
        self.dc.clienttxt.SetLabel("Alors Client = " + filtre["Client",int(hip)] )
        self.dc.activitetxt.SetLabel("Et Prestation = " + filtre["Prestation",int(hip)] )

    def chargeFiltres(self):
        global filtre,message
        try:
            try:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
                logfile = open(chemFS,'rb')
            except:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
                logfile = open(chemFS,'rb')
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            #print repr(drunk)
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            #print repr(drink)
            xim=xml.dom.minidom.parseString(drink)
            logfile.close()
            unem = xim.getElementsByTagName('FILTRE')
            x=1
            filtre['nombre']=0
            for unam in unem:
                filtre['Libelle',x]=unam.getAttribute('Libelle')
                filtre['nombre']=x
                filtre['Contenant',x]=unam.getAttribute('Contenant')
                filtre['Propriete',x]=unam.getAttribute('Propriete')
                filtre['Contenu',x]=unam.getAttribute('Contenu')
                filtre['Client',x]=unam.getAttribute('Client')
                filtre['Prestation',x]=unam.getAttribute('Prestation')
                filtre['Prestationid',x]=unam.getAttribute('Prestationid')
                filtre["checked",x]=False
                x+=1
        except:
            message="Erreur dansle chargement des filtres"
                
    def chargeDonnees(self):
        global listeclient,listeactivite,message,poste,presta
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            fft=open(TchemFSF, mode ='rb')
            output = StringIO.StringIO(fft.read())
            decoutput=StringIO.StringIO()
            #output.write(fft.read())
            fft.close()
            def Gdecrypt(output,decoutput):
                global jak
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=output.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                decoutput.write(rep)
                return decoutput
 
            Gdecrypt(output,decoutput)
            lines={}
            lines = decoutput.getvalue()
            #print 'lines-'+repr(lines)
            #lo=len(lines)
            #lines = decoutput.readlines()
            #print decoutput.getvalue()
            p=0
            poste={}
            presta={}
            l=0
            poste["PID"]=""
            poste["ID"]=""
            poste["posteNAME"]=""
            poste["Date"]=""
            poste["GUID"]=""
            poste["ADMINID"]=""
            T=False
            for char in lines:
                if char=='\t':
                    p+=1
                    continue
                if char=='\n':
                    break
                if p==0 and l==0:poste["PID"]=poste["PID"]+char
                if p==1 and l==0:poste["ID"]=poste["ID"]+char
                if p==2 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                if p==3 and l==0:poste["Date"]=poste["Date"]+char
                if p==4 and l==0:poste["GUID"]=poste["GUID"]+char
                if p==5 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
            if poste["ADMINID"]!="":    
                conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                conn = psycopg2.connect(conn_string)
                curs = conn.cursor()
                result=curs.execute("SELECT nomsoc FROM clients WHERE idadmin='"+str(poste["ADMINID"])+"';" )
                result=curs.fetchall()
                xlisteclient.append('Le client en question')
                if result:
                    for chain in result:
                        Tclient=""
                        for char in chain:
                            Tclient=Tclient+str(char)
                        xlisteclient.append(str(Tclient).decode('utf-8'))
                presult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='0';")
                presult=curs.fetchall()
                presta['1','count']=0
                presta['2','count']=0
                presta['2','count']=0
                xlisteactivite.append('La prestation en question')
                if presult:
                    u=1
                    for pchain in presult:
                        #print chain
                        p=0
                        T0presta=""
                        T0idpresta=""
                        for pchar in pchain:
                            if p==0:T0presta=T0presta+str(pchar)
                            if p==1:T0idpresta=T0idpresta+str(pchar)
                            p+=1
                        xlisteactivite.append(str(T0presta).decode('utf-8'))
                        presta[u,'0','0','label']=T0presta
                        presta[u,'0','0','id']=T0idpresta
                        presta['1','count']=u
                        ppresult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='1' AND mother='"+str(T0idpresta)+"';" )
                        ppresult=curs.fetchall()
                        if ppresult:
                            v=1
                            for ppchain in ppresult:
                                #print chain
                                pp=0
                                T1presta=""
                                T1idpresta=""
                                for ppchar in ppchain:
                                    if pp==0:T1presta=T1presta+str(ppchar)
                                    if pp==1:T1idpresta=T1idpresta+str(ppchar)
                                    pp+=1
                                xlisteactivite.append('  --  '+str(T1presta).decode('utf-8'))
                                presta[u,v,'0','label']='  --  '+str(T1presta).decode('utf-8')
                                presta[u,v,'0','id']=T1idpresta
                                presta['2','count']=v
                                pppresult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='2' AND mother='"+str(T1idpresta)+"';" )
                                pppresult=curs.fetchall()
                                if pppresult:
                                    w=1
                                    for pppchain in pppresult:
                                        #print chain
                                        ppp=0
                                        T2presta=""
                                        T2idpresta=""
                                        for pppchar in pppchain:
                                            if ppp==0:T2presta=T2presta+str(pppchar)
                                            if ppp==1:T2idpresta=T2idpresta+str(pppchar)
                                            ppp+=1
                                        xlisteactivite.append('  --  --  '+str(T2presta).decode('utf-8'))
                                        presta[u,v,w,'label']='  --  --  '+str(T2presta).decode('utf-8')
                                        presta[u,v,w,'id']=T2idpresta
                                        presta['3','count']=w
            
                                        w+=1            
                                v+=1
                        u+=1

                curs.close()
                conn.close()
            else:
                message="erreur : Faites le wizard avant"
        except:
            message="Connection internet requise"
        

    def ajouteFiltre(self,event):
        global Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,xlisteclient,xlisteactivite,listetache,message,filtre,fbox
        tpass=False
        if Tcontenant!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez selectionner un contenant")
        if tpass==False:
            return
        tpass=False
        if Tpropriete!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez selectionner une propriété")
        if tpass==False:
            return
        tpass=False
        if Tfiltre!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez entrer un libellé au filtre")
        if tpass==False:
            return
        tpass=False
        if Tcontenu!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez entrer la valeur contenue")
        if tpass==False:
            return
        tpass=False
        if Tclient!="":
            tpass=True
        else:
            self.dc.message.SetLabel("Veuillez selectionner une valeur pour client")
        if tpass==False:
            return
        tpass=True
        if Tclient=="Le client en question":
            if Tcontenu=="Le nom du client":
                tpass=True
            else:
                self.dc.message.SetLabel("La valeur 'Le nom du client' doit être selectionnée\n dans le contenu pour cette fonction")
                tpass=False
        if tpass==False:
            return
        tpass=True
        if Tprestation=="La prestation en question":
            if Tcontenu=="Le nom de la prestation":
                tpass=True
            else:
                self.dc.message.SetLabel("La valeur 'Le nom de la prestation' doit être \n selectionnée dans le contenu pour cette fonction")
                tpass=False
        if tpass==False:
            return
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            logfile = open(chemFS,'rb')
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        #result.write(detr)
        drunk=result.getvalue()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        unem = xim.getElementsByTagName('FILTRE')
        for unam in unem:
            libelle=unam.getAttribute('Libelle')
            if libelle==Tfiltre:
                self.dc.message.SetLabel("libellé de filtre déjà utilisé")
                return
        print 'gorl'                    
        racine=xim.documentElement
        element =xim.createElement("FILTRE")
        element.setAttribute("Libelle",Tfiltre)
        element.setAttribute("Contenant",Tcontenant)
        element.setAttribute("Propriete",Tpropriete)
        element.setAttribute("Contenu",Tcontenu)
        element.setAttribute("Client",Tclient)
        element.setAttribute("Prestation",Tprestation)
        element.setAttribute("Prestationid",Tprestationid)
        racine.appendChild(element)
##        unem = xim.getElementsByTagName('FILTRE')
##        for x in range(1,int(filtre['nombre'])+1):
##            #print x
##            posy=(int(x)*10)
##            idx='235'+str(x)
##            self.dc.postboxp.Detach(fbox[x])
        #self.dc.postboxp.Clear(True)
        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO()
        xim.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,chemFS)
        outputin.close()
        results.close()
        #self.ajouteFiltres()
        self.Destroy()
        Analyse(None, 460, 'Chronos Monitor',"Filtre ajouté")


    def ajouteFiltres(self):
        global filtre,fbox
        #self.dc.postboxp.Clear(True)
        for x in range(1,int(filtre['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=str(x)
            fbox[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(filtre['Libelle',int(x)]))
            self.dc.postboxp.Add(fbox[x],wx.LEFT)
            fbox[x].Bind(wx.EVT_CHECKBOX, self.OnFiltreCheck)
        #self.dc.postboxp.ShowItems(True)
    
    def retireFiltre(self,event):
        global filtre
        try:
            try:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
                logfile = open(chemFS,'rb')
            except:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
                logfile = open(chemFS,'rb')
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            #print repr(drunk)
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            #print repr(drink)
            xim=xml.dom.minidom.parseString(drink)
            logfile.close()
            unem = xim.getElementsByTagName('FILTRE')
            racine=xim.documentElement
            for x in range(1,int(filtre['nombre'])+1):
                if filtre["checked",x]==True:
                    for unam in unem:
                        libelle=unam.getAttribute('Libelle')
                        if libelle==filtre['Libelle',x]:
                            racine.removeChild(unam)
                            #print "removed"
            def Gencrypt(results,outputfile):
                encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                mlogfile = open(outputfile, 'wb')
                ret=''
                while True:
                    chunk = results.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )                
                    ret=ret+chunk
                djunky=encryptor.encrypt(ret)
                mlogfile.write(djunky)
                mlogfile.close()
            class TTransPak:
                def write(self,data):
                    outputin.write(data.encode('utf-8'))
            outputin = StringIO.StringIO()
            xim.writexml(TTransPak(), encoding='utf-8')
            results = StringIO.StringIO(outputin.getvalue())        
            Gencrypt(results,chemFS)
            outputin.close()
            results.close()
            self.Destroy()
            Analyse(None, 460, 'Chronos Monitor',"Filtres retirés")
        except:
            self.dc.message.SetLabel("erreur dans la gestion des filtres")
                            
    def messageLu(self,event):
        self.dc.message.SetLabel("")

##pnl1 = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
##pnl2 = wx.Panel(self, -1, style=wx.RAISED_BORDER)
##pnl3 = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
##pnl4 = wx.Panel(self, -1, style=wx.NO_BORDER) http://wiki.wxpython.org/AnotherTutorial#wx.GridBagSizer
  
    def Draw(self):
        global filtre,listeclient,listeactivite,fbox,message
        self.dc.SetFont(self.font)
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
       #wx.NullColour)
        #==================Panel Definition De Filtre=======================================
        self.dc.SetFont(self.dc.font1)
        self.dc.paneldefinition = wx.Panel ( self,-1,(10,30),(420,110), style=wx.SUNKEN_BORDER)
        self.dc.paneldefinition.SetBackgroundColour('#EAEAE9')
        self.dc.ajouter = wx.Button ( self.dc.paneldefinition, 100, 'Ajouter' ,pos=(335,80) )
        self.dc.ajouter.Bind(wx.EVT_BUTTON, self.ajouteFiltre )
        self.dc.lu = wx.Button ( self.dc.paneldefinition,-1, 'Lu' ,pos=(270,80), size=(30, 20))
        self.dc.lu.Bind(wx.EVT_BUTTON, self.messageLu )
        self.dc.plus = wx.Button ( self.dc.paneldefinition,-1, '+' ,pos=(300,80), size=(30, 20))
        self.dc.plus.Bind(wx.EVT_BUTTON, self.importexport )
        self.dc.si=wx.StaticText(self.dc.paneldefinition, -1, label="Si :",pos=(3,8))
        self.dc.si.SetBackgroundColour('#EAEAE9')
        self.dc.alors=wx.StaticText(self.dc.paneldefinition, -1, label="Alors :",pos=(3,32))
        self.dc.alors.SetBackgroundColour('#EAEAE9')
        self.dc.message = wx.StaticText(self.dc.paneldefinition, -1, message,pos=(3,79))
        self.dc.message.SetBackgroundColour('#EAEAE9')
        self.dc.libelleclient=wx.StaticText(self.dc.paneldefinition, -1, label="Client = ",pos=(36,32))
        self.dc.libelleclient.SetBackgroundColour('#EAEAE9')
        self.dc.libelleactivite=wx.StaticText(self.dc.paneldefinition, -1, label="Prestation = ",pos=(3,57))
        self.dc.libelleactivite.SetBackgroundColour('#EAEAE9')
        #self.dc.libelletache = wx.StaticText(self.dc.paneldefinition, -1, 'Tache =',pos=(3,85))
        #self.dc.libelletache.SetBackgroundColour('#EAEAE9')
        self.dc.libellefiltre = wx.StaticText(self.dc.paneldefinition, -1, 'Libellé du filtre :',pos=(250,32))
        self.dc.libellefiltre.SetBackgroundColour('#EAEAE9')
        contenants = ['Le libellé de la fenêtre', 'Le chemin du processus', 'Le nom du processus', 'Le chemin du fichier', 'Le nom du fichier']
        self.dc.contenants = wx.ComboBox(self.dc.paneldefinition, 2856, size=(125, -1),pos=(22,5), choices=contenants, style=wx.CB_READONLY)
        self.dc.contenants.Bind(wx.EVT_COMBOBOX, self.OnContSelect)
        propriete = ['contient', 'est égal à']
        self.dc.propriete = wx.ComboBox(self.dc.paneldefinition, 2857, size=(73, -1),pos=(152,5), choices=propriete, style=wx.CB_READONLY)
        self.dc.propriete.Bind(wx.EVT_COMBOBOX, self.OnPropSelect)
        xcontenu=['Le nom du client','Le nom de la prestation']
        self.dc.contenu=wx.ComboBox(self.dc.paneldefinition, 2858, size=(185, -1),pos=(230,5), choices=xcontenu)
        self.dc.contenu.Bind(wx.EVT_TEXT, self.OnContenuSelect)
        self.dc.nomfiltre=wx.TextCtrl(self.dc.paneldefinition, 2859, size=(85, -1),pos=(330,30))
        self.dc.nomfiltre.Bind(wx.EVT_TEXT, self.OnFiltreSelect)

        self.dc.client = wx.ComboBox(self.dc.paneldefinition, 2860, size=(165,-1),pos=(77,30), choices=xlisteclient, style=wx.CB_READONLY | wx.EXPAND )
        self.dc.client.Bind(wx.EVT_COMBOBOX, self.OnClientSelect)
        self.dc.activite = wx.ComboBox(self.dc.paneldefinition, 2861, size=(345, -1),pos=(70,55), choices=xlisteactivite, style=wx.CB_READONLY)
        self.dc.activite.Bind(wx.EVT_COMBOBOX, self.OnPrestaSelect)



        #==================Panel Liste de Filtres===========================================,pos=(10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,150),(150,120), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond, 10, 300, True)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        fbox={}
        for x in range(1,int(filtre['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=str(x)
            fbox[x]=wx.CheckBox(self.dc.panelp,int(idx),label=filtre['Libelle',int(x)])
            self.dc.postboxp.Add(fbox[x],wx.LEFT)
            fbox[x].Bind(wx.EVT_CHECKBOX, self.OnFiltreCheck)
        self.dc.export = wx.Button ( self, 100, 'Retirer',pos=(170,248) )
        self.dc.export.Bind(wx.EVT_BUTTON, self.retireFiltre )
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)
        #=================Panel Affichage du Filtre==========================================
        self.dc.panel = wx.Panel ( self,-1,(170,150),(260,90), style=wx.SUNKEN_BORDER)
        self.dc.panel.SetBackgroundColour('#EAEAE9')
        self.dc.contenanttxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,5))
        self.dc.contenanttxt.SetBackgroundColour('#EAEAE9')
        self.dc.contenutxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,25))
        self.dc.contenutxt.SetBackgroundColour('#EAEAE9')
        self.dc.clienttxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,45))
        self.dc.clienttxt.SetBackgroundColour('#EAEAE9')
        self.dc.activitetxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,65))
        self.dc.activitetxt.SetBackgroundColour('#EAEAE9')



        self.Show ( True )
        
    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)

        event.Skip()


    def OnDraw(self):
        self.chargeFiltres()
        self.chargeDonnees()
        self.Draw()        
        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
            self.Close()
                
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            enter=True
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.validr)
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                enter=False          

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()
class AnalyseIE(wx.Frame):
    global jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtrex,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,xlisteclient,xlisteactivite,listetache,dusers,user_id,usersecretid,poste,xfiltrex,deltatrsp
    def __init__(self, parent, id, title,messagem):
        global jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,filtrex,Tcontenant,Tcontenu,Tpropriete,Tfiltre,Tclient,Tprestation,Tprestationid,xlisteclient,xlisteactivite,listetache,dusers,user_id,usersecretid,poste,xfiltrex,deltatrsp
        
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/analyse.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/analyse-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/analyse-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap('img/analyse-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap('img/analyse-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap('img/analyse-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        filtrex={}
        xfiltrex={}
        checkfichier={}
        jak='2164691737824342'
        filtrex['nombre']=0
        xfiltrex['nombre']=0
        Tcontenant=""
        Tcontenu=""
        Tpropriete=""
        Tfiltre=""
        Tclient=""
        Tprestation=""
        Ttache=""
        Tprestationid=""
        xlisteclient = ['non défini']
        xlisteactivite = ['non défini']
        message=messagem

        
        

        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Rendez Vous sur :"
        line2="http://www.chronosmonitor.fr"
        line3="Pour obtenir une clef d'activation"  
        enter=False         
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.validRegion = wx.RegionFromBitmap(self.valid)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.validRegion.IntersectRegion(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
      

        self.dc = wx.ClientDC(self)
        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        self.Centre()

        self.OnDraw()

    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):

        pass

    def OnRadio(self,event):
        pass
        
    def OnApply(self,event):
        pass
    
    def Export(self,event):
        pass

    def OnTTexT(self,event):
        global dtp
        dtp=event.GetString()

    def OnContSelect(self,event):
        global Tcontenant
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tcontenant=user.GetValue()

    def OnPropSelect(self,event):
        global Tpropriete
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tpropriete=user.GetValue()

    def OnContenuSelect(self,event):
        global Tcontenu
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tcontenu=user.GetValue()

    def OnFiltreSelect(self,event):
        global Tfiltre
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tfiltre=user.GetValue()

    def OnClientSelect(self,event):
        global Tclient
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tclient=user.GetValue()

    def OnPrestaSelect(self,event):
        global Tprestation,presta,Tprestationid
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Tprestation=user.GetValue()
        ft=len(Tprestation)
        if int(ft)>10 and Tprestation[0:10]=='  --  --  ':
            for x in range(1,presta['1','count']+1):
                for t in range(1,presta['2','count']+1):
                    for r in range(1,presta['3','count']+1):
                        try:
                            if presta[x,t,r,'label']==Tprestation:
                                Tprestationid=presta[x,t,r,'id']
                        except:
                            pass
        elif int(ft)>6 and Tprestation[0:6]=='  --  ':                
            for x in range(1,presta['1','count']+1):
                for t in range(1,presta['2','count']+1):
                    try:
                        if presta[x,t,'0','label']==Tprestation:
                            Tprestationid=presta[x,t,'0','id']
                    except:
                        pass
        else:                
            for x in range(1,presta['1','count']+1):
                try:
                    if presta[x,'0','0','label']==Tprestation:
                        Tprestationid=presta[x,'0','0','id']
                except:
                    pass
    def OnTacheSelect(self,event):
        global Ttache
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        Ttache=user.GetValue()


    def OnFiltreCheck(self,event):
        global filtrex
        uzer=event.GetId()
##        p=0
        hip=uzer
##        for char in str(uzer):
##            if p >2:
##                hip=hip+char
##            p+=1
        if filtrex["checked",int(hip)]==False:
            filtrex["checked",int(hip)]=True

        else:
            filtrex["checked",int(hip)]=False


        self.dc.contenanttxt.SetLabel(filtrex["Libelle",int(hip)] + ": Si "+filtrex["Contenant",int(hip)] )
        self.dc.contenutxt.SetLabel(filtrex["Propriete",int(hip)] + ' "'+  filtrex["Contenu",int(hip)]+'"' )
        self.dc.clienttxt.SetLabel("Alors Client = " + filtrex["Client",int(hip)] )
        self.dc.activitetxt.SetLabel("Et Prestation = " + filtrex["Prestation",int(hip)] )
    def OnxFiltreCheck(self,event):
        global xsfiltrex
        uzer=event.GetId()
##        p=0
        hip=uzer
##        for char in str(uzer):
##            if p >2:
##                hip=hip+char
##            p+=1
        if xfiltrex["checked",int(hip)]==False:
            xfiltrex["checked",int(hip)]=True
        else:
            xfiltrex["checked",int(hip)]=False


        self.dc.contenanttxt.SetLabel(xfiltrex["Libelle",int(hip)] + ": Si "+xfiltrex["Contenant",int(hip)] )
        self.dc.contenutxt.SetLabel(xfiltrex["Propriete",int(hip)] + ' "'+  xfiltrex["Contenu",int(hip)]+'"' )
        self.dc.clienttxt.SetLabel("Alors Client = " + xfiltrex["Client",int(hip)] )
        self.dc.activitetxt.SetLabel("Et Prestation = " + xfiltrex["Prestation",int(hip)] )
    def chargeFiltres(self):
        global filtrex,message
        try:
            try:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
                logfile = open(chemFS,'rb')
            except:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
                logfile = open(chemFS,'rb')
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            #print repr(drunk)
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            #print repr(drink)
            xim=xml.dom.minidom.parseString(drink)
            logfile.close()
            unem = xim.getElementsByTagName('FILTRE')
            x=1
            filtrex['nombre']=0
            for unam in unem:
                filtrex['Libelle',x]=unam.getAttribute('Libelle')
                filtrex['nombre']=x
                filtrex['Contenant',x]=unam.getAttribute('Contenant')
                filtrex['Propriete',x]=unam.getAttribute('Propriete')
                filtrex['Contenu',x]=unam.getAttribute('Contenu')
                filtrex['Client',x]=unam.getAttribute('Client')
                filtrex['Prestation',x]=unam.getAttribute('Prestation')
                filtrex['Prestationid',x]=unam.getAttribute('Prestationid')
                filtrex["checked",x]=False
                x+=1
        except:
            message="Erreur dansle chargement des filtres"
                
    def chargeDonnees(self):
        global listeclient,listeactivite,message,poste,presta,dusers,user_id,usersecretid,xfiltrex
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            fft=open(TchemFSF, mode ='rb')
            output = StringIO.StringIO(fft.read())
            decoutput=StringIO.StringIO()
            #output.write(fft.read())
            fft.close()
            def Gdecrypt(output,decoutput):
                global jak
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=output.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                decoutput.write(rep)
                return decoutput
 
            Gdecrypt(output,decoutput)
            lines={}
            lines = decoutput.getvalue()
            #print 'lines-'+repr(lines)
            #lo=len(lines)
            #lines = decoutput.readlines()
            #print decoutput.getvalue()
            p=0
            poste={}
            presta={}
            l=0
            poste["PID"]=""
            poste["ID"]=""
            poste["posteNAME"]=""
            poste["Date"]=""
            poste["GUID"]=""
            poste["ADMINID"]=""
            T=False
            for char in lines:
                if char=='\t':
                    p+=1
                    continue
                if char=='\n':
                    break
                if p==0 and l==0:poste["PID"]=poste["PID"]+char
                if p==1 and l==0:poste["ID"]=poste["ID"]+char
                if p==2 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                if p==3 and l==0:poste["Date"]=poste["Date"]+char
                if p==4 and l==0:poste["GUID"]=poste["GUID"]+char
                if p==5 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
            if poste["ADMINID"]!="":
                if dusers['sfiltre']=='1':
                    usersecretid=user_id
                else:
                    usersecretid=0
                conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                conn = psycopg2.connect(conn_string)
                conn.set_client_encoding('UTF8')
                curs = conn.cursor()
                result=curs.execute("SELECT libelle, contenant, contenu, propriete,client, prestation, prestationid FROM filtres WHERE secret='0' AND adminid='"+str(poste["ADMINID"])+"';" )
                rresult=curs.fetchall()
                if rresult:
                    x=1
                    for rchain in rresult:
                        p=0
                        xfiltrex['Libelle',x]=""
                        xfiltrex['nombre']=x
                        xfiltrex['Contenant',x]=""
                        xfiltrex['Propriete',x]=""
                        xfiltrex['Contenu',x]=""
                        xfiltrex['Client',x]=""
                        xfiltrex['Prestation',x]=""
                        xfiltrex['Prestationid',x]=""
                        xfiltrex["checked",x]=False
                        for rrchar in rchain:
                            if p==0:xfiltrex['Libelle',x]=xfiltrex['Libelle',x]+str(rrchar).decode('utf-8')
                            if p==1:xfiltrex['Contenant',x]=xfiltrex['Contenant',x]+str(rrchar).decode('utf-8')
                            if p==2:xfiltrex['Contenu',x]=xfiltrex['Contenu',x]+str(rrchar).decode('utf-8')
                            if p==3:xfiltrex['Propriete',x]=xfiltrex['Propriete',x]+str(rrchar).decode('utf-8')
                            if p==4:xfiltrex['Client',x]=xfiltrex['Client',x]+str(rrchar).decode('utf-8')
                            if p==5:xfiltrex['Prestation',x]=xfiltrex['Prestation',x]+str(rrchar).decode('utf-8')
                            if p==6:xfiltrex['Prestationid',x]=xfiltrex['Prestationid',x]+str(rrchar).decode('utf-8')
                            p+=1
                        x+=1
                if usersecretid!=0:
                    result=curs.execute("SELECT libelle, contenant, contenu, propriete,client, prestation, prestationid FROM filtres WHERE secret='"+usersecretid+"' AND adminid='"+str(poste["ADMINID"])+"';" )
                    rresult=curs.fetchall()
                    if rresult:
                        for rchain in rresult:
                            #print chain
                            p=0
                            xfiltrex['Libelle',x]=""
                            xfiltrex['nombre']=x
                            xfiltrex['Contenant',x]=""
                            xfiltrex['Propriete',x]=""
                            xfiltrex['Contenu',x]=""
                            xfiltrex['Client',x]=""
                            xfiltrex['Prestation',x]=""
                            xfiltrex['Prestationid',x]=""
                            xfiltrex["checked",x]=False
                            for rrchar in rchain:
                                if p==0:xfiltrex['Libelle',x]=xfiltrex['Libelle',x]+str(rrchar)
                                if p==1:xfiltrex['Contenant',x]=xfiltrex['Contenant',x]+str(rrchar)
                                if p==2:xfiltrex['Contenu',x]=xfiltrex['Contenu',x]+str(rrchar)
                                if p==3:xfiltrex['Propriete',x]=xfiltrex['Propriete',x]+str(rrchar)
                                if p==4:xfiltrex['Client',x]=xfiltrex['Client',x]+str(rrchar)
                                if p==5:xfiltrex['Prestation',x]=xfiltrex['Prestation',x]+str(rrchar)
                                if p==6:xfiltrex['Prestationid',x]=xfiltrex['Prestationid',x]+str(rrchar)
                                p+=1
                            x+=1                    
                result=curs.execute("SELECT nomsoc FROM clients WHERE idadmin='"+str(poste["ADMINID"])+"';" )
                result=curs.fetchall()
                xlisteclient.append('Le client en question')
                if result:
                    for chain in result:
                        Tclient=""
                        for char in chain:
                            Tclient=Tclient+str(char)
                        xlisteclient.append(str(Tclient).decode('utf-8'))
                presult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='0';")
                presult=curs.fetchall()
                presta['1','count']=0
                presta['2','count']=0
                presta['2','count']=0
                xlisteactivite.append('La prestation en question')
                if presult:
                    u=1
                    for pchain in presult:
                        #print chain
                        p=0
                        T0presta=""
                        T0idpresta=""
                        for pchar in pchain:
                            if p==0:T0presta=T0presta+str(pchar)
                            if p==1:T0idpresta=T0idpresta+str(pchar)
                            p+=1
                        xlisteactivite.append(str(T0presta).decode('utf-8'))
                        presta[u,'0','0','label']=T0presta
                        presta[u,'0','0','id']=T0idpresta
                        presta['1','count']=u
                        ppresult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='1' AND mother='"+str(T0idpresta)+"';" )
                        ppresult=curs.fetchall()
                        if ppresult:
                            v=1
                            for ppchain in ppresult:
                                #print chain
                                pp=0
                                T1presta=""
                                T1idpresta=""
                                for ppchar in ppchain:
                                    if pp==0:T1presta=T1presta+str(ppchar)
                                    if pp==1:T1idpresta=T1idpresta+str(ppchar)
                                    pp+=1
                                xlisteactivite.append('  --  '+str(T1presta).decode('utf-8'))
                                presta[u,v,'0','label']='  --  '+str(T1presta).decode('utf-8')
                                presta[u,v,'0','id']=T1idpresta
                                presta['2','count']=v
                                pppresult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='2' AND mother='"+str(T1idpresta)+"';" )
                                pppresult=curs.fetchall()
                                if pppresult:
                                    w=1
                                    for pppchain in pppresult:
                                        #print chain
                                        ppp=0
                                        T2presta=""
                                        T2idpresta=""
                                        for pppchar in pppchain:
                                            if ppp==0:T2presta=T2presta+str(pppchar)
                                            if ppp==1:T2idpresta=T2idpresta+str(pppchar)
                                            ppp+=1
                                        xlisteactivite.append('  --  --  '+str(T2presta).decode('utf-8'))
                                        presta[u,v,w,'label']='  --  --  '+str(T2presta).decode('utf-8')
                                        presta[u,v,w,'id']=T2idpresta
                                        presta['3','count']=w
            
                                        w+=1            
                                v+=1
                        u+=1

                curs.close()
                conn.close()

            else:
                message="erreur : Faites le wizard avant"
        except:
            message="Connection internet requise"
        

    def importFiltre(self,event):
        global message,xfiltrex
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            logfile = open(chemFS,'rb')
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        #result.write(detr)
        drunk=result.getvalue()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        unem = xim.getElementsByTagName('FILTRE')
        for unam in unem:
            libelle=unam.getAttribute('Libelle')
            if libelle==Tfiltre:
                self.dc.message.SetLabel("libellé de filtre déjà utilisé")
                return                   
        racine=xim.documentElement
        for x in range(1,int(xfiltrex['nombre'])+1):
            if xfiltrex["checked",x]==True:
                element =xim.createElement("FILTRE")
                element.setAttribute("Libelle",xfiltrex["Libelle",x])
                element.setAttribute("Contenant",xfiltrex["Contenant",x])
                element.setAttribute("Propriete",xfiltrex["Propriete",x])
                element.setAttribute("Contenu",xfiltrex["Contenu",x])
                element.setAttribute("Client",xfiltrex["Client",x])
                element.setAttribute("Prestation",xfiltrex["Prestation",x])
                element.setAttribute("Prestationid",xfiltrex["Prestationid",x])
                racine.appendChild(element)

        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO()
        xim.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,chemFS)
        outputin.close()
        results.close()
        #self.ajouteFiltres()
        self.Destroy()
        try:
            frame=wx.FindWindowById(460)
            if frame.IsShown():
                frame.Close()
        except:
            pass
        Analyse(None, 460, 'Chronos Monitor Analyse',"Filtres importés")
        AnalyseIE(None, 472, 'Chronos Monitor Import Export Filtres',"Filtres importés")


    def ajouteFiltres(self):
        global filtrex,xfbox
        #self.dc.postboxp.Clear(True)
        for x in range(1,int(filtre['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=str(x)
            xfbox[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(filtrex['Libelle',int(x)]))
            self.dc.postboxp.Add(fbox[x],wx.LEFT)
            xfbox[x].Bind(wx.EVT_CHECKBOX, self.OnFiltreCheck)
        #self.dc.postboxp.ShowItems(True)
    
    def exportFiltre(self,event):
        global filtrex,poste,dusers,user_id,usersecretid
##        try:
##            try:
##                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
##                logfile = open(chemFS,'rb')
##            except:
##                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
##                logfile = open(chemFS,'rb')
##                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
##            def Gdecrypt(outputin,result):
##                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
##                chunksize=(64*1024)
##                rep=''
##                while True:
##                    chunk=''
##                    chunk=outputin.read(n=chunksize)
##                    if len(chunk)==0:
##                        break
##                    elif len(chunk)%16!=0:
##                        chunk += ' ' * (16-len(chunk) % 16 )
##                    rep=rep+xdecryptor.decrypt(chunk)
##                logfile.close()
##                result.write(rep)
##                return result
##                        
##            outputin = StringIO.StringIO(logfile.read())
##    ##                        outputin.write(logfile.read())
##            result = StringIO.StringIO()
##            #detr=obj.decrypt(outputin.getvalue())
##            Gdecrypt(outputin,result)
##            #result.write(detr)
##            drunk=result.getvalue()
##            lou=len(drunk)
##            drink=''
##            #print repr(drunk)
##            for c in range(0,lou):
##                try:
##                    if drunk[c:c+7]=='</PrsP>':
##                        drink=drink+'</PrsP>'
##                        break
##                    else:drink=drink+drunk[c]
##                except:
##                    pass
##            #print repr(drink)
##            xim=xml.dom.minidom.parseString(drink)
##            logfile.close()
##            unem = xim.getElementsByTagName('FILTRE')
##            racine=xim.documentElement
        conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
        conn = psycopg2.connect(conn_string)
        conn.set_client_encoding('UTF8')
        curs = conn.cursor()
        for x in range(1,int(filtrex['nombre'])+1):
            if filtrex["checked",x]==True:
                strin="""INSERT INTO filtres (libelle, contenant, contenu, propriete,client, prestation, prestationid, secret, adminid) VALUES """
                result=curs.execute("SELECT * FROM filtres WHERE libelle='"+filtrex['Libelle',x]+"' AND contenant='"+filtrex['Contenant',x]+"' AND contenu='"+filtrex['Contenu',x]+"' AND propriete='"+filtrex['Propriete',x]+"' AND client='"+filtrex['Client',x]+"' AND prestationid='"+filtrex['Prestationid',x]+"' AND adminid='"+str(poste['ADMINID'])+"' AND secret='"+str(usersecretid)+"';" )
                rresult=curs.fetchall()
                if rresult:
                    pass
                else:
                    strin=strin+"('"+filtrex['Libelle',x]+"','"+filtrex['Contenant',x]+"','"+filtrex['Contenu',x]+"','"+filtrex['Propriete',x]+"','"+filtrex['Client',x]+"','"+filtrex['Prestation',x]+"','"+filtrex['Prestationid',x]+"','"+str(usersecretid)+"','"+str(poste['ADMINID'])+"');"                                                                                                              

                    try:
                        result=curs.execute(strin)
                        conn.commit()
                        print strin
                    except:
                        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                        print "Database connection failed!\n ->%s" % (exceptionValue)

##                    for unam in unem:
##                        libelle=unam.getAttribute('Libelle')
##                        if libelle==filtre['Libelle',x]:
##                            racine.removeChild(unam)
##                            #print "removed"
##            def Gencrypt(results,outputfile):
##                encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
##                #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
##                chunksize=(64*1024)
##                mlogfile = open(outputfile, 'wb')
##                ret=''
##                while True:
##                    chunk = results.read(n=chunksize)
##                    if len(chunk)==0:
##                        break
##                    elif len(chunk)%16!=0:
##                        chunk += ' ' * (16-len(chunk) % 16 )                
##                    ret=ret+chunk
##                djunky=encryptor.encrypt(ret)
##                mlogfile.write(djunky)
##                mlogfile.close()
##            class TTransPak:
##                def write(self,data):
##                    outputin.write(data.encode('utf-8'))
##            outputin = StringIO.StringIO()
##            xim.writexml(TTransPak(), encoding='utf-8')
##            results = StringIO.StringIO(outputin.getvalue())        
##            Gencrypt(results,chemFS)
##            outputin.close()
##            results.close()
        self.Destroy()
        AnalyseIE(None, 472, 'Chronos Monitor Import Export Filtres',"Filtres Exportés")
##        except:
##            self.dc.message.SetLabel("Veuillez vous connecter à internet pour exporter vos filtres")
                            
    def messageLu(self,event):
        self.dc.message.SetLabel("")

##pnl1 = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
##pnl2 = wx.Panel(self, -1, style=wx.RAISED_BORDER)
##pnl3 = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)
##pnl4 = wx.Panel(self, -1, style=wx.NO_BORDER) http://wiki.wxpython.org/AnotherTutorial#wx.GridBagSizer
  
    def Draw(self):
        global filtrex,listeclient,listeactivite,xfbox,message,xfiltrex
        self.dc.SetFont(self.font)
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
       #wx.NullColour)
        #==================Panel Definition De Filtre=======================================
        self.dc.SetFont(self.dc.font1)
        self.dc.DrawText("Filtres Locaux :",10,140)
        self.dc.DrawText("Filtres Serveur :",170,140)
        self.dc.panel = wx.Panel ( self,-1,(10,30),(420,110), style=wx.SUNKEN_BORDER)
        self.dc.panel.SetBackgroundColour('#EAEAE9')
        self.dc.contenanttxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,5))
        self.dc.contenanttxt.SetBackgroundColour('#EAEAE9')
        self.dc.contenutxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,25))
        self.dc.contenutxt.SetBackgroundColour('#EAEAE9')
        self.dc.clienttxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,45))
        self.dc.clienttxt.SetBackgroundColour('#EAEAE9')
        self.dc.activitetxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,65))
        self.dc.activitetxt.SetBackgroundColour('#EAEAE9')
##        self.dc.ajouter = wx.Button ( self.dc.paneldefinition, 100, 'Ajouter' ,pos=(335,80) )
##        self.dc.ajouter.Bind(wx.EVT_BUTTON, self.ajouteFiltre )
        self.dc.lu = wx.Button ( self.dc.panel, -1, 'Lu' ,pos=(380,80), size=(30, 20))
        self.dc.lu.Bind(wx.EVT_BUTTON, self.messageLu )
##        self.dc.si=wx.StaticText(self.dc.paneldefinition, -1, label="Si :",pos=(3,8))
##        self.dc.si.SetBackgroundColour('#EAEAE9')
##        self.dc.alors=wx.StaticText(self.dc.paneldefinition, -1, label="Alors :",pos=(3,32))
##        self.dc.alors.SetBackgroundColour('#EAEAE9')
        self.dc.message = wx.StaticText(self.dc.panel, -1, message,pos=(3,85))
        self.dc.message.SetBackgroundColour('#EAEAE9')
##        self.dc.libelleclient=wx.StaticText(self.dc.paneldefinition, -1, label="Client = ",pos=(36,32))
##        self.dc.libelleclient.SetBackgroundColour('#EAEAE9')
##        self.dc.libelleactivite=wx.StaticText(self.dc.paneldefinition, -1, label="Prestation = ",pos=(3,57))
##        self.dc.libelleactivite.SetBackgroundColour('#EAEAE9')
##        #self.dc.libelletache = wx.StaticText(self.dc.paneldefinition, -1, 'Tache =',pos=(3,85))
##        #self.dc.libelletache.SetBackgroundColour('#EAEAE9')
##        self.dc.libellefiltre = wx.StaticText(self.dc.paneldefinition, -1, 'Libellé du filtre :',pos=(250,32))
##        self.dc.libellefiltre.SetBackgroundColour('#EAEAE9')
##        contenants = ['Le libellé de la fenêtre', 'Le chemin du processus', 'Le nom du processus', 'Le chemin du fichier', 'Le nom du fichier']
##        self.dc.contenants = wx.ComboBox(self.dc.paneldefinition, 2856, size=(125, -1),pos=(22,5), choices=contenants, style=wx.CB_READONLY)
##        self.dc.contenants.Bind(wx.EVT_COMBOBOX, self.OnContSelect)
##        propriete = ['contient', 'est égal à']
##        self.dc.propriete = wx.ComboBox(self.dc.paneldefinition, 2857, size=(73, -1),pos=(152,5), choices=propriete, style=wx.CB_READONLY)
##        self.dc.propriete.Bind(wx.EVT_COMBOBOX, self.OnPropSelect)
##        xcontenu=['Le nom du client','Le nom de la prestation']
##        self.dc.contenu=wx.ComboBox(self.dc.paneldefinition, 2858, size=(185, -1),pos=(230,5), choices=xcontenu)
##        self.dc.contenu.Bind(wx.EVT_TEXT, self.OnContenuSelect)
##        self.dc.nomfiltre=wx.TextCtrl(self.dc.paneldefinition, 2859, size=(85, -1),pos=(330,30))
##        self.dc.nomfiltre.Bind(wx.EVT_TEXT, self.OnFiltreSelect)
##
##        self.dc.client = wx.ComboBox(self.dc.paneldefinition, 2860, size=(165,-1),pos=(77,30), choices=xlisteclient, style=wx.CB_READONLY | wx.EXPAND )
##        self.dc.client.Bind(wx.EVT_COMBOBOX, self.OnClientSelect)
##        self.dc.activite = wx.ComboBox(self.dc.paneldefinition, 2861, size=(345, -1),pos=(70,55), choices=xlisteactivite, style=wx.CB_READONLY)
##        self.dc.activite.Bind(wx.EVT_COMBOBOX, self.OnPrestaSelect)



        #==================Panel Liste de Filtres===========================================,pos=(10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,155),(150,120), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond, 10, 300, True)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        xfbox={}
        for x in range(1,int(filtrex['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=str(x)
            xfbox[x]=wx.CheckBox(self.dc.panelp,int(idx),label=filtrex['Libelle',int(x)])
            self.dc.postboxp.Add(xfbox[x],wx.LEFT)
            xfbox[x].Bind(wx.EVT_CHECKBOX, self.OnFiltreCheck)
        self.dc.export = wx.Button ( self, 100, 'Export',pos=(165,248) )
        self.dc.export.Bind(wx.EVT_BUTTON, self.exportFiltre )
        self.dc.eimport = wx.Button ( self, 100, 'Import',pos=(240,248) )
        self.dc.eimport.Bind(wx.EVT_BUTTON, self.importFiltre )
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)
        #=================Panel Affichage du Filtre==========================================
        self.dc.panelei = scrolled.ScrolledPanel ( self,-1,(170,155),(260,90), style=wx.SUNKEN_BORDER)
        self.dc.panelei.SetBackgroundColour('#EAEAE9')
        self.dc.panelei.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.DrawBitmap(self.fond, 10, 300, True)
        self.dc.epostboxp=wx.BoxSizer(wx.VERTICAL)
        exfbox={}
        for x in range(1,int(xfiltrex['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=str(x)
            exfbox[x]=wx.CheckBox(self.dc.panelei,int(idx),label=xfiltrex['Libelle',int(x)])
            self.dc.epostboxp.Add(exfbox[x],wx.LEFT)
            exfbox[x].Bind(wx.EVT_CHECKBOX, self.OnxFiltreCheck)
        self.dc.panelei.SetSizer(self.dc.epostboxp)
        self.dc.epostboxp.FitInside(self.dc.panelei)
##        self.dc.contenanttxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,5))
##        self.dc.contenanttxt.SetBackgroundColour('#EAEAE9')
##        self.dc.contenutxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,25))
##        self.dc.contenutxt.SetBackgroundColour('#EAEAE9')
##        self.dc.clienttxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,45))
##        self.dc.clienttxt.SetBackgroundColour('#EAEAE9')
##        self.dc.activitetxt = wx.StaticText(self.dc.panel, -1, "",pos=(5,65))
##        self.dc.activitetxt.SetBackgroundColour('#EAEAE9')



        self.Show ( True )
        
    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)

        event.Skip()

    def OnDraw(self):
        self.chargeFiltres()
        self.chargeDonnees()
        self.Draw()        

        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
            self.Close()
                
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            enter=True
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.validr)
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                enter=False          

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()




class Export(wx.Frame):
    global reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,encfile,checkfichier,deltatrsp
    def __init__(self, parent, id, title):
        global reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,encfile,checkfichier,deltatrsp
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/export.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/export-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/export-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap('img/dossier-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap('img/export-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        encfile={}
        checkfichier={}
        jak='2164691737824342'
        

        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Rendez Vous sur :"
        line2="http://www.chronosmonitor.fr"
        line3="Pour obtenir une clef d'activation"  
        enter=False         
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.validRegion = wx.RegionFromBitmap(self.valid)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.validRegion.IntersectRegion(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
      
        #self.dc=wx.BufferedDC(wx.ClientDC(self),self.bitmap)
        self.dc = wx.ClientDC(self)
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        self.Centre()
        self.OnDraw()



    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):

        pass

    def OnRadio(self,event):
        pass
        





    def OnApply(self,event):
        pass
    
    def Export(self,event):
        pass

    def OnTTexT(self,event):
        global dtp
        dtp=event.GetString()

    def OnDTexT(self,event):
        global dina
        dina=event.GetString()



    def OnFichierCheck(self,event):
        global checkfichier
        uzer=event.GetId()
##        p=0
        hip=int(uzer)
##        for char in str(uzer):
##            if p >3:
##                hip=str(hip)+str(char)
##            p+=1
##        print hip
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            checkfichier["Checked",int(hip)]=True
        else:
            checkfichier["Checked",int(hip)]=False

    def DShow(self):
        self.dc.DrawText("Choisissez les fichiers à exporter :",10,30)

    def chargeFichiers(self):
        global encfile
        x=1
        encdir=os.curdir+os.sep+'wok'+os.sep+'enc'
        for f in os.listdir(encdir):
            if os.path.isdir(os.path.join(encdir, f)):
                chemr=os.path.join(encdir, f)
                for fic in os.listdir(chemr):
                    if os.path.isfile(os.path.join(chemr, fic)):
                        chem=os.path.join(chemr, fic)
                        flo=len(chem)
                        fichier=""
                        for fm in range(0,flo-4):
                            if chem[fm]==os.sep:
                                fichier=""
                            else:
                                fichier=fichier+chem[fm]

                        encfile['path',x]=fichier
                        encfile['nombre']=x
                        checkfichier["Checked",x]=False
                        x+=1

    def Export(self,event):
        global obj,encfile,checkfichier
        try:
            message="erreur lors de l'exportation"
            encdir=os.curdir+os.sep+'wok'+os.sep+'enc'
            for f in os.listdir(encdir):
                if os.path.isdir(os.path.join(encdir, f)):
                    chemr=os.path.join(encdir, f)
                    for fic in os.listdir(chemr):
                        if os.path.isfile(os.path.join(chemr, fic)):
                            chem=os.path.join(chemr, fic)
                            flo=len(chem)
                            fichier=""
                            for fm in range(0,flo-4):
                                if chem[fm]==os.sep:
                                    fichier=""
                                else:
                                    fichier=fichier+chem[fm]
                            nochecked=False
                            for x in range(1,int(encfile['nombre'])+1):
                                if encfile['path',x]==fichier:
                                    if checkfichier["Checked",x]==False:
                                        nochecked=True
                            if nochecked==True:
                                continue
                            tze=1
                            rrept=chem
                            xil=len(chem)

                            tze=0
                            rrept=chem
                            logfile = open(rrept, mode ='rb')
                            def Gdecrypt(outputin,result):
                                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                                chunksize=(64*1024)
                                rep=''
                                while True:
                                    chunk=''
                                    chunk=outputin.read(n=chunksize)
                                    if len(chunk)==0:
                                        break
                                    elif len(chunk)%16!=0:
                                        chunk += ' ' * (16-len(chunk) % 16 )
                                    rep=rep+xdecryptor.decrypt(chunk)
                                logfile.close()
                                result.write(rep)
                                return result
                                        
                            outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
                            result = StringIO.StringIO()
                            #detr=obj.decrypt(outputin.getvalue())
                            Gdecrypt(outputin,result)
                            #result.write(detr)
                            drunk=result.getvalue()
                            lou=len(drunk)
                            drink=''
                            #print repr(drunk)
                            for c in range(0,lou):
                                try:
                                    if drunk[c:c+7]=='</PrsP>':
                                        drink=drink+'</PrsP>'
                                        break
                                    else:drink=drink+drunk[c]
                                except:
                                    pass
                            #print repr(drink)
                            XTCstring=xml.dom.minidom.parseString(drink)
                            outputin.close()
                            result.close()
                            x=0
                            ligne={}
                            lino={}
                            kp=len(fic)
                            chemt=os.curdir+os.sep+'export'+os.sep+fic[0:kp-4]+'.csv'
                            
                            logfile = open(chemt, mode ='w')
                            def MTWrite(data):
                                logfile.write(data.encode('iso-8859-1'))
                            lines = XTCstring.getElementsByTagName('PrsP')
                            for line in lines:
                                ligne[x]=line.getAttribute('ReportLine')#.decode('iso-8859-1')
                                lino[x]=""
                                line=ligne[x]
                                ln=len(line)
                                
                                for w in range(0,ln):
                                    char=line[w:w+1]
                                    icar=line[w:w+2]
                                    if char=="#":
                                        lino[x]=lino[x]+'\t'
                                    else:
                                        lino[x]=lino[x]+char
                                x+=1

                            for c in range(0,x):
                                MTWrite(lino[c]+'\n')
                            logfile.close()
        finally:
            message="Les fichiers ont été exportés dans le dossier export"
        self.dc.message.SetLabel(message)


 
    def Lu(self,event):
        self.dc.message.SetLabel('')




    
    def Draw(self):
        global encfile
        self.dc.SetFont(self.font)
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
       #wx.NullColour)
        #self.dc.SetTextForeground()
        self.dc.SetFont(self.dc.font1)
        self.dc.SetTextBackground(wx.NullColour)
        self.dc.SetTextForeground('#6C8D91')
        self.dc.DrawText("Choisissez les fichiers à exporter :",10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,50),(200,120), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond, 10, 300, True)
        #self.dc.panel=MyScrollPanel(self.dc)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        self.dc.box={}
        for x in range(1,int(encfile['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx=int(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(encfile['path',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnFichierCheck)
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)
        self.dc.panel = wx.Panel ( self,-1,(10,170),(400,70), style=wx.SUNKEN_BORDER)
        self.dc.panel.SetBackgroundColour('#EAEAE9')
        self.dc.message = wx.StaticText(self.dc.panel, -1, '',pos=(10,10))
        self.dc.export = wx.Button ( self.dc.panel, 100, 'Export',pos=(10,30) )
        self.dc.export.Bind(wx.EVT_BUTTON, self.Export )
        self.dc.lu = wx.Button ( self.dc.panel, 100, 'Lu',pos=(100,30) )
        self.dc.lu.Bind(wx.EVT_BUTTON, self.Lu )
        self.Show ( True )
        
    def OnPaint(self, event):
        global postes,users,dc,box,panelp

        wx.BufferedPaintDC(self,self.bitmap)
##        self.chargeFichiers()
##        self.Draw()
        self.DShow()
        event.Skip()


    def OnDraw(self):
##        wx.BufferedPaintDC(self,self.bitmap)
        self.chargeFichiers()
        self.Draw() 
        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
##            self.verifyTransparency()
##            self.verifyDina()
##            try:
##                self.saveConfig()
##                try:
##                    if str(vtp)=="OK":
##                        reset=True
##                        line1="Configuration enregistrée."
##                        line2="Le widget la prendra en compte"
##                        line3="d'içi 10 secondes."
##                        self.Close()
##                        WizardEnd(None, 465, 'Chronos Monitor Configuration')
##                    elif str(vtp)=="NOT":
##                        self.dc.message.SetLabel(message)
##                except:
##                    self.dc.message.SetLabel(message)
##            except:
##                self.dc.message.SetLabel(message)
            self.Close()
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            self.DShow()
            enter=True
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.validr)
            self.DShow()
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                self.DShow()
                enter=False          

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

class Dossiers(wx.Frame):
    global reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,dossier,undossier,explorer,logfull,deltatrsp
    def __init__(self, parent, id, title):
        global reset,jak,dina,message,vtp,line1,line2,line3,ElChaloR,oscurdir,dossier,undossier,explorer,path,logfull,deltatrsp
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/parametres_0.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/dossier-normal.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/dossier-close.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.valida = wx.Bitmap('img/dossier-appui.png', wx.BITMAP_TYPE_PNG)
        self.validr = wx.Bitmap('img/dossier-rollover.png', wx.BITMAP_TYPE_PNG)
        self.valid = wx.Bitmap('img/valider-normal.png', wx.BITMAP_TYPE_PNG)
        self.fond = wx.Bitmap('img/wizard-fond.png', wx.BITMAP_TYPE_PNG)

        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        dossier={}
        undossier={}
        jak='2164691737824342'
        

        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()

        line1="Rendez Vous sur :"
        line2="http://www.chronosmonitor.fr"
        line3="Pour obtenir une clef d'activation"  
        enter=False
        path=""
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.validRegion = wx.RegionFromBitmap(self.valid)
        self.closeRegion = wx.RegionFromBitmap(self.close)


        self.validRegion.IntersectRegion(self.bitmapRegion)
        self.validRegion.Offset(316, 242)

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(408, 12)
      
        self.dc = wx.ClientDC(self)
        #self.dc=wx.BufferedDC(wx.ClientDC(self),self.bitmap)
        self.Show(True)
        self.Fit()
        self.Centre()
        message='Choisissez les dossiers a superviser'

        self.OnDraw()

    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()


    def OnKey(self,event):

        pass

    def OnRadio(self,event):
        pass
        





    def OnApply(self,event):
        pass
    
    def Export(self,event):
        pass

    def OnPathSelect(self,event):
        global path
        path=event.GetString()

    def OnDTexT(self,event):
        global dina
        dina=event.GetString()



    def OnDossierCheck(self,event):
        global undossier
        uzer=event.GetId()
        p=0
        hip=""
        for char in str(uzer):
            if p >2:
                hip=hip+char
            p+=1
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            undossier["Checked",int(hip)]=True
        else:
            undossier["Checked",int(hip)]=False


    def OnExplorerCheck(self,event):
        global explorer
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            explorer=True
        else:
            explorer=False

    def OnLogFullCheck(self,event):
        global logfull
        uzer=event.GetId()
        user = wx.FindWindowById(int(uzer))
        if user.GetValue():
            logfull=True
        else:
            logfull=False
            
    def chargeDossier(self):
        global dossier,path,logfull
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            logfile = open(chemFS,'rb')
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        #result.write(detr)
        drunk=result.getvalue()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        racine=xim.documentElement
        unem = xim.getElementsByTagName('DIR')
        x=1
        dossier['nombre']=0
        for unam in unem:
            dossier['path',x]=unam.getAttribute('PATH')
            dossier['nombre']=x
##            print dossier['path',x]
            x+=1
  
    def newDir(self,event):
        global i,root,UserButton,dvariable,explorer,logfull
        desktop_pidl = shell.SHGetFolderLocation (0, shellcon.CSIDL_DESKTOP, 0, 0)
        pidl, display_name, image_list = shell.SHBrowseForFolder (
          win32gui.GetDesktopWindow (),
          desktop_pidl,
          "Choissez un repertoire",
          0,
          None,
          None
        )
        if shell.SHGetPathFromIDList (pidl)=="":
          mes.set(u"aucun repertoire selectionné")
          return
        else:path=shell.SHGetPathFromIDList (pidl)
##        try:
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            logfile = open(chemFS,'rb')
            zero=False
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            zero=True
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        outputin.close()
        #result.write(detr)
        drunk=result.getvalue()
        result.close()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()

        racine=xim.documentElement
        element =xim.createElement("DIR")
        element.setAttribute("PATH",str(path))
        racine.appendChild(element)
 

        outputin = StringIO.StringIO()
        xim.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())

        Gencrypt(results,chemFS)
        outputin.close()
        results.close()

        self.Destroy()
        Dossiers(None, -1, 'Chronos Monitor')
  




    def dirDelete(self,event):
        global undossier
        #try:
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            logfile = open(chemFS,'rb')
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        #result.write(detr)
        drunk=result.getvalue()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        racine=xim.documentElement
        unem = xim.getElementsByTagName('DIR')
        x=1
        for unam in unem:
            hlog=unam.getAttribute('PATH')
            try:
                if undossier["Checked",int(x)]==True:
                    racine.removeChild(unam)
            except:
                pass
            x+=1

        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO()
        xim.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,chemFS)
        outputin.close()
        results.close()

        self.Destroy()
        Dossiers(None, -1, 'Chronos Monitor')

    def dunlog(self):
        global dossier
        #try:
        for x in range(0,int(dossier['nombre'])):
            print 'dunlog',x
            idx='480'+str(x)
        self.dc.postboxp.Clear()
    
        #except:
        #    print 'erreur dunlog'


    def bakPath(self,event):
        global path
        desktop_pidl = shell.SHGetFolderLocation (0, shellcon.CSIDL_DESKTOP, 0, 0)
        pidl, display_name, image_list = shell.SHBrowseForFolder (
          win32gui.GetDesktopWindow (),
          desktop_pidl,
          "Choissez un repertoire",
          0,
          None,
          None
        )
        if shell.SHGetPathFromIDList (pidl)=="":
          mes.set("aucun repertoire selectionne")
          path=""
        else:path=shell.SHGetPathFromIDList (pidl)
        self.dc.bakpath.SetValue(path)
        
    def dreinit(self):
        global dossier
        for x in range(1,int(dossier['nombre'])+1):
            posy=(int(x)*10)
            idx='480'+str(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(dossier['path',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnDossierCheck)

    def DShow(self):
        self.dc.DrawText("Choisissez les dossiers à surveiller :",10,30)

    
    def Draw(self):
        global dossier,explorer,path,logfull
        self.dc.SetFont(self.font)
        self.dc.font1 = wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
       #wx.NullColour)
        #self.dc.SetTextForeground()
        self.dc.SetFont(self.dc.font1)
        self.dc.DrawText("Choisissez les dossiers à surveiller :",10,30)
        self.dc.panelp=scrolled.ScrolledPanel(self,-1,(10,50),(400,100), style=wx.SUNKEN_BORDER)
        self.dc.panelp.SetupScrolling(scroll_x=True,scroll_y=True)
        self.dc.panelp.SetBackgroundColour('#EAEAE9')
        self.dc.DrawBitmap(self.fond, 10, 300, True)
        #self.dc.panel=MyScrollPanel(self.dc)
        self.dc.postboxp=wx.BoxSizer(wx.VERTICAL)
        self.dc.box={}
        for x in range(1,int(dossier['nombre'])+1):
            #print x
            posy=(int(x)*10)
            idx='480'+str(x)
            self.dc.box[x]=wx.CheckBox(self.dc.panelp,int(idx),label=str(dossier['path',int(x)]))
            self.dc.postboxp.Add(self.dc.box[x],wx.LEFT)
            self.dc.box[x].Bind(wx.EVT_CHECKBOX, self.OnDossierCheck)
        self.dc.panelp.SetSizer(self.dc.postboxp)
        self.dc.postboxp.FitInside(self.dc.panelp)
        self.dc.panel = wx.Panel ( self,-1,(10,170),(50,100), style=wx.SUNKEN_BORDER)
        self.dc.panel.SetBackgroundColour('#EAEAE9')
        self.dc.sizer = wx.GridBagSizer ( 2, 1 )
        self.dc.message = wx.StaticText(self.dc.panel, -1, '')
        self.dc.newdir = wx.Button ( self.dc.panel, 100, 'Nouveau Dossier' )
        self.dc.newdir.Bind(wx.EVT_BUTTON, self.newDir )
        self.dc.nodir = wx.Button ( self.dc.panel, 100, 'Retirer Dossier' )
        self.dc.nodir.Bind(wx.EVT_BUTTON, self.dirDelete )
        self.dc.sizer.Add ( self.dc.message, ( 1, 0 ) )
        self.dc.sizer.Add ( self.dc.nodir, ( 2, 0 ) )
        self.dc.sizer.Add ( self.dc.newdir, ( 2, 1 ) )
        self.dc.horizontal = wx.BoxSizer ( wx.HORIZONTAL )
        self.dc.horizontal.Add ( ( 0, 0 ), 1 )
        self.dc.horizontal.Add ( self.dc.sizer )
        self.dc.horizontal.Add ( ( 0, 0 ), 1 )
        self.dc.vertical = wx.BoxSizer ( wx.VERTICAL )
        self.dc.vertical.Add ( ( 0, 0, ), 1 )
        self.dc.vertical.Add ( self.dc.horizontal, 0, wx.ALIGN_CENTER )
        self.dc.vertical.Add ( ( 0, 0 ), 1 )
        self.dc.panel.SetSizerAndFit ( self.dc.vertical )
        self.Show ( True )
        #print '1'
        
    def OnPaint(self, event):
        #global postes,users,dc,box,panelp

        wx.BufferedPaintDC(self,self.bitmap)
        self.DShow()
        #self.Draw()
        event.Skip()

    def OnDraw(self):
        #wx.BufferedPaintDC(self,self.bitmap)
        #wx.BufferedDC(wx.ClientDC(self),self.bitmap)
        self.chargeDossier()
        self.Draw()
        

    def saveConfig(self):
        self.Destroy()



        
    def OnLeftDown(self, event):
        global message,vtp,line1,line2,line3,reset
        #self.bdc = wx.BufferedDC(self.cdc)
        pos = event.GetPosition()
##        self.dc.nkey.SelectAll()
##        self.key = self.dc.nkey.GetValue()
##        self.dc.nkey.Clear()
#        print "+"+repr(self.key)+"+"
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.valida)
            try:
                self.saveConfig()
                try:
                        reset=True
                        line1="Configuration enregistrée."
                        line2="Le programme la prendra en compte"
                        line3="au prochain démarrage"
                        self.Close()
                        try:
                            dialogframe = wx.FindWindowById(465)
                            dialogframe.Close()
                            WizardEnd(None, 465, 'Chronos Monitor Dossiers')            
                        except:
                            WizardEnd(None, 465, 'Chronos Monitor Dossiers')
                except:
                    self.dc.message.SetLabel(message)
            except:
                self.dc.message.SetLabel(message)
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter,line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.closer)
            self.DShow()
            enter=True
        elif self.validRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.validr)
            self.DShow()
            enter=True
        else:
            if enter==True:
                wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                self.DShow()
                enter=False          

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()


class Options(wx.Frame):
    global enter,dusers,line1,line2,line3,deltatrsp
    def __init__(self, parent, id, title):
        global enter,dusers,line1,line2,line3,deltatrsp
        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/option_0.gif'
        self.bmp = wx.Bitmap(self.image_file, wx.BITMAP_TYPE_GIF)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/option_0.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/wizard-normal.png', wx.BITMAP_TYPE_PNG)
        self.wizarda = wx.Bitmap('img/option_ass_appui.png', wx.BITMAP_TYPE_PNG)
        self.wizardr = wx.Bitmap('img/option_ass_rollover.png', wx.BITMAP_TYPE_PNG)
        self.usersa = wx.Bitmap('img/option_ge_appui.png', wx.BITMAP_TYPE_PNG)
        self.usersr = wx.Bitmap('img/option_ge_rollover.png', wx.BITMAP_TYPE_PNG)
        self.dossiersa = wx.Bitmap('img/option_su_appui.png', wx.BITMAP_TYPE_PNG)
        self.dossiersr = wx.Bitmap('img/option_su_rollover.png', wx.BITMAP_TYPE_PNG)
        self.closer = wx.Bitmap('img/option_close_rollover.png', wx.BITMAP_TYPE_PNG)
        self.analysea = wx.Bitmap('img/option_an_appui.png', wx.BITMAP_TYPE_PNG)
        self.analyser = wx.Bitmap('img/option_an_rollover.png', wx.BITMAP_TYPE_PNG)
        self.parama = wx.Bitmap('img/option_para_appui.png', wx.BITMAP_TYPE_PNG)
        self.paramr = wx.Bitmap('img/option_para_rollover.png', wx.BITMAP_TYPE_PNG)
        self.wizard = wx.Bitmap('img/wizard-normal.png', wx.BITMAP_TYPE_PNG)
        self.users = wx.Bitmap('img/users-normal.png', wx.BITMAP_TYPE_PNG)
        self.dossiers = wx.Bitmap('img/dossiers-normal.png', wx.BITMAP_TYPE_PNG)
        self.close = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.analyse = wx.Bitmap('img/dossiers-normal.png', wx.BITMAP_TYPE_PNG)
        self.param = wx.Bitmap('img/para_0.png', wx.BITMAP_TYPE_PNG)
        
        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))

        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()


        enter=False         
        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        #self.SetTransparent(220)
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.wizardRegion = wx.RegionFromBitmap(self.wizard)
        self.usersRegion = wx.RegionFromBitmap(self.users)
        self.dossiersRegion = wx.RegionFromBitmap(self.dossiers)
        self.closeRegion = wx.RegionFromBitmap(self.close)
        self.analyseRegion = wx.RegionFromBitmap(self.analyse)
        self.paramRegion = wx.RegionFromBitmap(self.param)


        self.wizardRegion.IntersectRegion(self.bitmapRegion)
        self.wizardRegion.Offset(22, 60)

        self.usersRegion.IntersectRegion(self.bitmapRegion)
        self.usersRegion.Offset(22, 92)

        self.dossiersRegion.IntersectRegion(self.bitmapRegion)
        self.dossiersRegion.Offset(22, 130)  

        self.closeRegion.IntersectRegion(self.bitmapRegion)
        self.closeRegion.Offset(201, 12)

        self.analyseRegion.IntersectRegion(self.bitmapRegion)
        self.analyseRegion.Offset(22, 170)

        self.paramRegion.IntersectRegion(self.bitmapRegion)
        self.paramRegion.Offset(117, 252)        
      
        self.dc=wx.BufferedDC(wx.ClientDC(self),self.bmp)
##        self.dc = wx.ClientDC(self)
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)
        self.Show(True)
        self.Fit()
        #self.panel=wx.Panel(self,-1)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        #MyButton(self,-1,(49,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')

        self.OnDraw()


    def OnClose(self, event):
        self.tskic.Destroy()
        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bmp)
        self.hasShape=self.SetShape(region)


    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()
    def Draw(self):
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')


    def OnPaint(self, event):
        wx.BufferedPaintDC(self,self.bitmap)
##        self.Draw()
        event.Skip()

        
    def OnDraw(self):
        #wx.BufferedPaintDC(self,self.bitmap)
        #wx.BufferedDC(wx.ClientDC(self),self.bitmap)
        self.Draw()  




    def OnLeftDown(self, event):
        global line1,line2,line3
        pos = event.GetPosition()
        if self.closeRegion.ContainsPoint(pos):
            self.Close()
        elif self.wizardRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.wizarda)
            if dusers['active']==False:
                try:
                    wizardframe = wx.FindWindowById(463)
                    if wizardframe.IsShown():
                        wizardframe.Show()
                except:WizardActivation(None, 463, 'Chronos Monitor Wizard')           
            elif dusers['config']=="0" :
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else: 
                try:
                    wizardframe = wx.FindWindowById(463)
                    if wizardframe.IsShown():
                        wizardframe.Show()
                except:WizardActivation(None, 463, 'Chronos Monitor Wizard')
        elif self.usersRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.usersa)
            if dusers['active']==False:
                line1="veuillez d'abord"
                line2="réaliser le wizard" 
                line3="pour configurer votre poste"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            elif dusers['config']=="0" :
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else: 
                try:
                    userframe = wx.FindWindowById(462)
                    if userframe.IsShown():
                        userframe.Show()
                except:UserSelect(None, 462, 'Chronos Monitor Utilisateurs')
        elif self.dossiersRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.dossiersa)
            if dusers['active']==False:
                line1="veuillez d'abord"
                line2="réaliser le wizard" 
                line3="pour configurer votre poste"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            elif dusers['config']=="0" :
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else: 
                try:
                    dosframe = wx.FindWindowById(461)
                    if dosframe.IsShown():
                        dosframe.Show()
                except:Dossiers(None, 461, 'Chronos Monitor Dossiers')
        elif self.analyseRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.analysea)
            if dusers['active']==False:
                line1="veuillez d'abord"
                line2="réaliser le wizard" 
                line3="pour configurer votre poste"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')  
            elif dusers['auto']=="0":
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else:
                try:
                    anaframe = wx.FindWindowById(460)
                    if anaframe.IsShown():
                        anaframe.Show()
                except:Analyse(None, 460, 'Chronos Monitor Analyse',"Construisez vos filtres")
        elif self.paramRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.parama)
            if dusers['active']==False:
                line1="veuillez d'abord"
                line2="réaliser le wizard" 
                line3="pour configurer votre poste"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
            elif dusers['config']=="0" and dusers['export']=="0":
                line1="action non autorisée"
                line2="demandez l'autorisation" 
                line3="à votre administrateur"
                try:
                    dialogframe = wx.FindWindowById(465)
                    dialogframe.Close()
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                except:
                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else:            
                try:
                    paramframe = wx.FindWindowById(459)
                    if paramframe.IsShown():
                        paramframe.Show()
                except:Parametres(None, 459, 'Chronos Monitor Parametres')
                
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global enter
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.closeRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.closer)
                enter=True
            elif self.wizardRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.wizardr)
                enter=True
            elif self.usersRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.usersr) 
                enter=True
            elif self.dossiersRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.dossiersr)
                enter=True
            elif self.analyseRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.analyser)
                enter=True
            elif self.paramRegion.ContainsPoint(pos):
                wx.BufferedDC(wx.ClientDC(self),self.paramr)
                enter=True
            else:
                if enter==True:
                    wx.BufferedDC(wx.ClientDC(self),self.bitmap)
                    enter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()        


class Widget(wx.Frame):
    global issyncro,tenter,line1,line2,line3,dusers,explorer,fanal,user_id,poste_pid,dossier,reset,ssyncro,deltatrsp,to,fl,cl,jak,filtre,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,anafennamin,anafennameq,obj,mlogfile,mclogfile,XCstring,XTstring,enter,timer,logfile, resac, bvariable,do,rept,crept,hm,wintexte,win,timec,nombrecliq,processactif,texte,prs,pprocess,powa,mes,starter,oscurdir,computer,logType,verbose,user,poste,watcher,user_id

    def __init__(self, parent, id, title):
        global issyncro,tenter,logfull,logpath,line1,line2,line3,dusers,explorer,fanal,user_id,poste_pid,dossier,reset,ssyncro,deltatrsp,to,fl,cl,jak,filtre,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,anafennamin,anafennameq,obj,mlogfile,mclogfile,XCstring,XTstring,timer,logfile, resac, bvariable,do,rept,crept,hm,win,texte,timec,nombrecliq,processactif,prs,pprocess,powa,mes,starter,oscurdir,computer,logType,verbose,user,poste,watcher,listeclient,listeactivite,user_id


        wx.Frame.__init__(self, parent, id, title, size=(250, 150),style=wx.FRAME_SHAPED |wx.FRAME_NO_TASKBAR|wx.NO_BORDER|wx.FULL_REPAINT_ON_RESIZE)

        self.font = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, 
		wx.FONTWEIGHT_BOLD, False, 'Comic Sans MS')

        #self.panel=wx.Panel(self,-1)

        self.hasShape=False
        self.delta=(0,0)

        self.image_file = 'img/window.png'
        self.bmp = wx.Bitmap(self.image_file)
        #bg=wx.StaticBitmap(self.panel, wx.ID_ANY, bmp, (0, 0))
        
        self.bitmap = wx.Bitmap('img/window.gif', wx.BITMAP_TYPE_GIF)
        self.cross = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.crossover = wx.Bitmap('img/fermer-rollover.png', wx.BITMAP_TYPE_PNG)
        self.reduce = wx.Bitmap('img/close-normal.png', wx.BITMAP_TYPE_PNG)
        self.reduceover = wx.Bitmap('img/minimize-rollover.png', wx.BITMAP_TYPE_PNG)
        self.syncr = wx.Bitmap('img/sync-normal2.png', wx.BITMAP_TYPE_PNG)
        self.sync = wx.Bitmap('img/sync.png', wx.BITMAP_TYPE_PNG)
        self.oversync = wx.Bitmap('img/sync-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onsync = wx.Bitmap('img/sync-appui.png', wx.BITMAP_TYPE_PNG)
        self.loginr = wx.Bitmap('img/login-normal.png', wx.BITMAP_TYPE_PNG)
        self.login = wx.Bitmap('img/login.png', wx.BITMAP_TYPE_PNG)
        self.overlogin = wx.Bitmap('img/login-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onlogin = wx.Bitmap('img/login-appui.png', wx.BITMAP_TYPE_PNG)
        self.logoutr = wx.Bitmap('img/logout-normal.png', wx.BITMAP_TYPE_PNG)
        self.logout = wx.Bitmap('img/logout.png', wx.BITMAP_TYPE_PNG)
        self.overlogout = wx.Bitmap('img/logout-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onlogout = wx.Bitmap('img/logout-appui.png', wx.BITMAP_TYPE_PNG)
        self.options = wx.Bitmap('img/options-normal.png', wx.BITMAP_TYPE_PNG)
        self.overoptions = wx.Bitmap('img/options-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onoptions = wx.Bitmap('img/options-appui.png', wx.BITMAP_TYPE_PNG)
        self.liste = wx.Bitmap('img/liste-normal.png', wx.BITMAP_TYPE_PNG)
        self.overliste = wx.Bitmap('img/liste-rollover.png', wx.BITMAP_TYPE_PNG)
        self.onliste = wx.Bitmap('img/liste-appui.png', wx.BITMAP_TYPE_PNG)
        #image_file = 'img/fond.png'
##        self.crossf = wx.Bitmap('img/close-fond.png', wx.BITMAP_TYPE_PNG)
##        self.syncf = wx.Bitmap('img/sync-fond.png', wx.BITMAP_TYPE_PNG)
##        self.loginf = wx.Bitmap('img/login-fond.png', wx.BITMAP_TYPE_PNG)
##        self.listef = wx.Bitmap('img/liste-fond.png', wx.BITMAP_TYPE_PNG)
##        self.logoutf = wx.Bitmap('img/logout-fond.png', wx.BITMAP_TYPE_PNG)
##        self.reducef = wx.Bitmap('img/minimize-fond.png', wx.BITMAP_TYPE_PNG)
##        self.optionsf = wx.Bitmap('img/options-fond.png', wx.BITMAP_TYPE_PNG)
        
        #bmp = wx.Bitmap(image_file)
        #self.bg=wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
        self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))
        fl=1
        cl=1
        if wx.Platform == '__WXGTK__':
            self.Bind(wx.EVT_WINDOW_CREATE, self.SetNoteShape)
        else: self.SetNoteShape()



        def get_main_dir():
            try:
                sys.frozen
            except AttributeError:
                path = sys.argv[0]
            else:
                path = sys.executable
            return os.path.dirname(os.path.abspath(path))

        oscurdir=get_main_dir()
        jour=time.strftime('%d')
        mois=time.strftime('%m')
        annee=time.strftime('%Y')
        pprocess={}
        pr=0
        mes=""
        dusers={}
        dusers['active']=False
        def ifexist(rept):
            try:
                trylogfile = open(rept, mode ='r')
                trylogfile.close()
                return True
            except:
                return False
        rep=oscurdir+os.sep+"wok"+os.sep+"enc"+os.sep+mois+annee+os.sep+annee+mois+jour
        t=0
        r=True
        if os.access(oscurdir+os.sep+"wok"+os.sep+"enc"+os.sep+mois+annee,os.F_OK)==True:
            while r==True:
                t=t+1
                rept=str(rep)+str(t)+'.gwh'
                r=ifexist(rept)
            r=True
            t=0
            while r==True:
                t=t+1
                crept=str(rep)+str(t)+'condensed.gwh'
                r=ifexist(crept)
            #logfile = open(rept, mode ='a+')
            #clogfile = open(crept, mode ='a+')

        else:
            os.mkdir(oscurdir+os.sep+"wok"+os.sep+"enc"+os.sep+mois+annee)
            while r==True:
                t=t+1
                rept=str(rep)+str(t)+'.gwh'
                r=ifexist(rept)
            r=True
            t=0
            while r==True:
                t=t+1
                crept=str(rep)+str(t)+'condensed.gwh'
                r=ifexist(crept)


        starter=True
        resac=""
        texte=''
        win=''
        timec=''
        nombrecliq=0
        winame=""
        nmes={}
        dossier={}
        fanal={}
        watcher={}
        nmes[0,'time']=""
        nmes[0,'mes']=""
        nmes[0,'q']=0
        processactif=""
        powa=False
        prs=0
        enter=False
        tenter=False
        explorer=False
        issyncro=False
        filtre={}
        hm = pyHook.HookManager()
        anaprocspathin={}
        anaprocspatheq={}
        anaprocsnamin={}
        anaprocsnameq={}
        anaficpathin={}
        anaficpatheq={}
        anaficnamin={}
        anaficnameq={}
        anafennamin={}
        anafennameq={}
        listeclient={}
        listeactivite={}
        listeclient['nombre']=0
        listeactivite['nombre']=0
        anaprocspathin['count']=0
        anaprocspatheq['count']=0
        anaprocsnamin['count']=0
        anaprocsnameq['count']=0
        anaficpathin['count']=0
        anaficpatheq['count']=0
        anaficnamin['count']=0
        anaficnameq['count']=0
        anafennamin['count']=0
        anafennameq['count']=0

        #MyButton(self.panel,-1,(47,168),'img/sync-normal.png','img/sync-rollover.png','img/appui-sync.png')
        self.SetTransparent(int(deltatrsp))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)

        self.bitmapRegion = wx.RegionFromBitmap(self.bitmap)
        self.crossRegion = wx.RegionFromBitmap(self.cross)
        self.crossoverRegion = wx.RegionFromBitmap(self.cross)
        self.syncRegion = wx.RegionFromBitmap(self.syncr)
        self.loginRegion = wx.RegionFromBitmap(self.loginr)
        self.logoutRegion = wx.RegionFromBitmap(self.logoutr)
        self.optionsRegion = wx.RegionFromBitmap(self.options)
        self.listeRegion = wx.RegionFromBitmap(self.liste)
        self.reduceRegion = wx.RegionFromBitmap(self.reduce)

        self.syncRegion.IntersectRegion(self.bitmapRegion)
        self.syncRegion.Offset(49, 168)

        self.loginRegion.IntersectRegion(self.bitmapRegion)
        self.loginRegion.Offset(117, 146)

        self.logoutRegion.IntersectRegion(self.bitmapRegion)
        self.logoutRegion.Offset(49, 146)  

        self.optionsRegion.IntersectRegion(self.bitmapRegion)
        self.optionsRegion.Offset(132, 260)

        self.listeRegion.IntersectRegion(self.bitmapRegion)
        self.listeRegion.Offset(10, 40)

        self.reduceRegion.IntersectRegion(self.bitmapRegion)
        self.reduceRegion.Offset(178, 40)

        self.crossoverRegion.IntersectRegion(self.bitmapRegion)
        self.crossoverRegion.Offset(192, 40)
        
        self.bitmapRegion.IntersectRegion(self.crossRegion)
        self.bitmapRegion.Offset(192, 40)

        timer=wx.Timer(self, -1)
        self.Bind(wx.EVT_TIMER, self.minuteLoop,timer)

##        timerF=wx.Timer(self, -1)
##        self.Bind(wx.EVT_TIMER, self.minuteSave,timerF)

##        timerD=wx.Timer(self, -1)
##        self.Bind(wx.EVT_TIMER, self.minuteLine,timerD)

        jak='2164691737824342'
        
        #def Tstart():
        def startX():
            global ElChalor,jak
            zrept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.gwh'
            logfile = open(zrept, mode ='rb')
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            #print repr(drunk)
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            #print repr(drink)
            xim=xml.dom.minidom.parseString(drink)
##            zrept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.xml'
##            logfile = open(zrept, mode ='r')
##            xim =xml.dom.minidom.parse(logfile)
##            logfile.close()
            return xim
        XTstring=startX()
        XCstring=startX()
        
        self.dc=wx.BufferedDC(wx.ClientDC(self),self.bmp)
        
##        self.dc = wx.ClientDC(self)
##        self.dc.DrawBitmap(self.bitmap, 0, 0, True)

#        self.dc.Clear()
        self.Show(True)
        self.Fit()

        self.tskic = MyTaskBarIcon(self) 
        self.Centre()
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        #obj=DES3.new(str(ElChaloR[0:24]), DES3.MODE_ECB)
        
        #obj=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
        self.OnDraw()
    def chargeDossier(self):
        global dossier,explorer,logpath,logfull,watcher,start,poste,user,rept,XTstring,fl
        try:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"resap.gwh"
            logfile = open(chemFS,'rb')
        except:
            chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
            logfile = open(chemFS,'rb')
        def Gdecrypt(outputin,result):
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=outputin.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            logfile.close()
            result.write(rep)
            return result
                    
        outputin = StringIO.StringIO(logfile.read())
##                        outputin.write(logfile.read())
        result = StringIO.StringIO()
        #detr=obj.decrypt(outputin.getvalue())
        Gdecrypt(outputin,result)
        #result.write(detr)
        drunk=result.getvalue()
        lou=len(drunk)
        drink=''
        #print repr(drunk)
        for c in range(0,lou):
            try:
                if drunk[c:c+7]=='</PrsP>':
                    drink=drink+'</PrsP>'
                    break
                else:drink=drink+drunk[c]
            except:
                pass
        #print repr(drink)
        class watch(Thread):
            global start,poste,user,rept,XTstring,fl
            def __init__(self,path_to_watch):
                Thread.__init__(self)
                self.path=path_to_watch
                self.setDaemon(1)
                self.start()
            def TSave(self):
                global XTstring,XCstring
                def Gencrypt(results,outputfile):
                    encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                    #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                    chunksize=(64*1024)
                    mlogfile = open(outputfile, 'wb')
                    ret=''
                    while True:
                        chunk = results.read(n=chunksize)
                        if len(chunk)==0:
                            break
                        elif len(chunk)%16!=0:
                            chunk += ' ' * (16-len(chunk) % 16 )                
                        ret=ret+chunk
                    djunky=encryptor.encrypt(ret)
                    mlogfile.write(djunky)
                    mlogfile.close()
                class TTransPak:
                    def write(self,data):
                        outputin.write(data.encode('utf-8'))
                outputin = StringIO.StringIO()
                XTstring.writexml(TTransPak(), encoding='utf-8')
                results = StringIO.StringIO(outputin.getvalue())        
                Gencrypt(results,rept)
                outputin.close()
                results.close()
            def minuteView(self,line):
                global user,poste
                def unchain(string):
                    result=""
                    if string:
                        x=len(string)            
                        for x in range(0,x):
                            if string[x] in ["'",'"']:
                                result=result+" "
                            elif string[x] in ["#"]:
                                pass
                            else:result=result+string[x]
                    return result


                def chain(string):
                    results=""
                    if string:
                        x=len(string)            
                        for x in range(0,x):
                            if string[x]in ["\\"]:results=results+string[x]+string[x]
                            else:results=results+string[x]
                    return results
                Txzorbl={}
                final={}
                ses=0
                p=0
                Txzorbl[p]=""
                ln=len(line)
                for x in range(0,ln):
                    char=line[x:x+1]
                    if char=="#":
                        p+=1
                        Txzorbl[p]=""
                    else:
                        Txzorbl[p]=Txzorbl[p]+char
                try:
                    hour=Txzorbl[1]
                    dateprem=hour[0:8]
                    date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
                    houre=hour[9:18]
                    procs=""
                    chemin=""
                    fen=""
                    ncl=0
                    datour=str(Txzorbl[1]) 
                    inscript=False
                    intostr="""INSERT INTO logview (date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """
                    action=Txzorbl[2]
                    
                    try:
                        userid=Txzorbl[6]
                    except:
                        userid=0
                    try:
                        postepid=Txzorbl[7]
                    except:
                        postepid=poste['PID']
                    try:
                        procs=chain(Txzorbl[5])
                    except:
                        procs="None"
                    try:
                        ncl=0
                        chemin=chain(unchain(Txzorbl[4]))
                        fen="None"
                    except:
                        chemin="None"
                        fen="None"
                    try:
                        ncl=chain(unchain(Txzorbl[3]))
                    except:
                        ncl=0
                    intostr=intostr+"('"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','','',"+action+",'"+userid+"','"+postepid+"','"+str(poste['ADMINID'])+"');"
                    inscript=True 
                    if inscript==True:
                        conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                        conn = psycopg2.connect(conn_string)
                        conn.set_client_encoding('UTF8')
                        curs = conn.cursor()
                        presult=curs.execute("SELECT action FROM logview WHERE userid='"+userid+"';")
                        rresult=curs.fetchone()
                        if rresult:
                            intostr="UPDATE logview SET date='"+str(date)+"', heure='" +str(houre)+"', nomfenetre='"+ fen+"', processus='"+ procs+"', chemin='"+chemin+"', clicks='"+str(ncl)+"', client='',activite='',action='"+str(action)+"',posteid='"+str(poste['PID'])+"',final_userid='"+poste['ADMINID']+"' WHERE userid='"+str(userid)+"';"
                        result=curs.execute(intostr)
                        conn.commit()
                        curs.close()
                        conn.close()
                except:
                    pass
            def Twrite(self,string):
                global rept,XTstring,fl
                try:
                    racine=XTstring.documentElement
                    element =XTstring.createElement("PrsP")
                    element.setAttribute('ReportLine',string)
                    racine.appendChild(element)
                    self.TSave()
                finally:
                    self.minuteView(string)
            def run(self):
                global fl,user,poste,nombrecliq
                def unchain(string):
                    result=""
                    if string:
                        x=len(string)            
                        for x in range(0,x):
                            if string[x] in ["'",'"']:
                                result=result+" "
                            elif string[x] in ["#"]:
                                pass
                            else:result=result+string[x]
                    return result
                ACTIONS = {
                  1 : "Created",
                  2 : "Deleted",
                  3 : "Updated",
                  4 : "Renamed from something",
                  5 : "Renamed to something"
                }
                # Thanks to Claudio Grondi for the correct set of numbers
                FILE_LIST_DIRECTORY = 0x0001
                hDir = win32file.CreateFile (
                  self.path,
                  FILE_LIST_DIRECTORY,
                  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
                  None,
                  win32con.OPEN_EXISTING,
                  win32con.FILE_FLAG_BACKUP_SEMANTICS,
                  None
                )
                while start==True:
                  #
                  # ReadDirectoryChangesW takes a previously-created
                  #  handle to a directory, a buffer size for results,
                  #  a flag to indicate whether to watch subtrees and
                  #  a filter of what changes to notify.
                  #
                  # NB Tim Juchcinski reports that he needed to up
                  #  the buffer size to be sure of picking up all
                  #  events when a large number of files were
                  #  deleted at once.
                  #
                  results = win32file.ReadDirectoryChangesW (
                    hDir,
                    1024,
                    True,
                    win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
                     win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
                     win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
                     win32con.FILE_NOTIFY_CHANGE_SIZE |
                     win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
                     win32con.FILE_NOTIFY_CHANGE_SECURITY,
                    None,
                    None
                  )
                  for action, file in results:
                    timec=time.strftime('%m/%d/%y %H:%M:%S')
                    hwnd = win32gui.GetForegroundWindow()
                    # we want the desktop window
                    objid = pyAA.Constants.OBJID_WINDOW
                    # get the object
                    ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
                    pr= ao.GetProcessAndThreadID()
                    p = psutil.Process(pr[0])
                    processactif=p.exe
                    full_filename = os.path.join (self.path, file)
                    resac=str(fl)+'#'+str(timec)+'#'+ACTIONS.get (action, "Unknown")+'#'+str(nombrecliq)+'#'+unchain(full_filename)+'#'+unchain(processactif)+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'\n'
                    fl+=1
                    #self.Twrite(resac)
                    self.Twrite(resac)
                    #print full_filename + ACTIONS.get (action, "Unknown") + processactif
        xim=xml.dom.minidom.parseString(drink)
        logfile.close()
        racine=xim.documentElement
        unem = xim.getElementsByTagName('DIR')
        x=1
        dossier['nombre']=0
        for unam in unem:
            dossier['path',x]=unam.getAttribute('PATH')
            dossier['nombre']=x
            watcher[x]=watch(dossier['path',x])
            x+=1
        unem = xim.getElementsByTagName('EXPLORER')
        explorer=False
        for unam in unem:
            explorer=unam.getAttribute('VALUE')
        if explorer=='False':
            explorer=False
        if explorer=='True':
            explorer=True
        punem = xim.getElementsByTagName('BACKPATH')
        logpath=""
        for punam in punem:
            logpath=punam.getAttribute('PATH')
        nunem = xim.getElementsByTagName('EXPLORER')
        logfull=False
        for nunam in nunem:
            logfull=nunam.getAttribute('VALUE')
        if logfull=='False':
            logfull=False
        if logfull=='True':
            logfull=True
       

    def Twrite(self,string):
        global rept,XTstring,fl
        try:
            racine=XTstring.documentElement
            element =XTstring.createElement("PrsP")
            element.setAttribute('ReportLine',string)
            racine.appendChild(element)
        finally:
            #self.minuteView(string)
            fl+=1
##        outputin = StringIO.StringIO()

    def makeZero(self):
        rept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.xml'
        zrept=oscurdir+os.sep+'wok'+os.sep+'need'+os.sep+'zero.gwh'
        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO()
        logfile = open(rept, mode ='r')
        xim =xml.dom.minidom.parse(logfile)
        xim.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,zrept)
        outputin.close()
        results.close()        

    def minuteSave(self,event):
        global XTstring,XCstring
        def Gencrypt(results,outputfile):
            encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            mlogfile = open(outputfile, 'wb')
            ret=''
            while True:
                chunk = results.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )                
                ret=ret+chunk
            djunky=encryptor.encrypt(ret)
            mlogfile.write(djunky)
            mlogfile.close()
        class TTransPak:
            def write(self,data):
                outputin.write(data.encode('utf-8'))
        outputin = StringIO.StringIO()
        XTstring.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,rept)
        outputin.close()
        results.close()
        outputin = StringIO.StringIO()
        XCstring.writexml(TTransPak(), encoding='utf-8')
        results = StringIO.StringIO(outputin.getvalue())        
        Gencrypt(results,crept)
        outputin.close()
        results.close()
        
    def Cwrite(self,string):
        global crept,XCstring,cl
        try:
            racine=XCstring.documentElement
            element =XCstring.createElement("PrsP")
            element.setAttribute('ReportLine',string)
            racine.appendChild(element)
        finally:
##            if str(syncro)=="True" and start==True:
            #self.minuteView(string)
            cl+=1

    def DShow(self):
        self.dc.message.Show()
        self.dc.message.SetValue(unicode(mes))
        self.dc.display.Show()
        
    def verifyConfig(self):
        global deltatrsp,oscurdir,jak,ElChaloR,ssyncro,analyse,question
        def Gdecrypt(output,decoutput):
            global jak,ElChaloR
            xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
            chunksize=(64*1024)
            rep=''
            while True:
                chunk=''
                chunk=output.read(n=chunksize)
                if len(chunk)==0:
                    break
                elif len(chunk)%16!=0:
                    chunk += ' ' * (16-len(chunk) % 16 )
                rep=rep+xdecryptor.decrypt(chunk)
            decoutput.write(rep)
            return decoutput
        glorb=False
        try:
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'config.gwh'
            fft=open(TchemFSF, mode ='rb')
            output = StringIO.StringIO(fft.read())
            decoutput=StringIO.StringIO()
            fft.close()
            Gdecrypt(output,decoutput)
            lines={}
            p=0
            lines = decoutput.getvalue()
            tsyncro=""
            tanalyse=""
            tquestion=""
            tdeltatrsp=""
            tdinac=""
            for char in lines:
                if char=='\t':
                    p+=1
                    continue
                if char=='\n':
                    glorb=True
                    break
                if p==0:
                    tsyncro=tsyncro+char
                if p==1:
                    tanalyse=tanalyse+char
                if p==2:
                    tquestion=tquestion+char
                if p==3:
                    tdeltatrsp=tdeltatrsp+char
                if p==4:
                    tdinac=tdinac+char

            decoutput.close()
            output.close()
            if glorb==True:
                if tsyncro=="True":ssyncro=True
                else:ssyncro=False
                if tanalyse=="True":analyse=True
                else:analyse=False
                if tquestion=="True":question=True
                else:question=False
                deltatrsp=tdeltatrsp
                dinac=tdinac
                self.SetTransparent(int(deltatrsp))
                self.Show(True)
        except:
            pass


    def minuteLine(self,event):
        global reset,start,ssyncro
        def syncroCheck():
            self.synchro()
        def messageCheck():
            pass
        if reset==True:
            try:
                self.verifyConfig()
                reset=False
            except:
                self.dc.message.SetValue(unicode(mes)+unicode('erreur config'))
        if str(ssyncro)=="True" and start==True:
            pass

##            syncroCheck()
##            try:
##                self.syncroCheck()
##            except:
##                self.dc.message.SetValue(unicode(mes)+unicode('erreur syncro'))
        try:
            messageCheck()
        except:
            self.dc.message.SetValue(unicode(mes)+unicode('erreur connec'))
    class minuteLoop(Thread):
        global crept,XCstring,cl,nombrecliq,resac,start,user,poste
        def __init__(self,event):
            Thread.__init__(self)
            self.setDaemon(1)
            self.start()    
##        
##    def minuteLoop(self,event):
##        global cl,nombrecliq,texte,computer,logType,verbose,winame,resac,logfile,do,watcher,start,pprocess,prs,processactif

        def CSave(self):
            global XCstring
            def Gencrypt(results,outputfile):
                encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                mlogfile = open(outputfile, 'wb')
                ret=''
                while True:
                    chunk = results.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )                
                    ret=ret+chunk
                djunky=encryptor.encrypt(ret)
                mlogfile.write(djunky)
                mlogfile.close()
            class TTransPak:
                def write(self,data):
                    outputin.write(data.encode('utf-8'))
            outputin = StringIO.StringIO()
            XCstring.writexml(TTransPak(), encoding='utf-8')
            results = StringIO.StringIO(outputin.getvalue())        
            Gencrypt(results,crept)
            outputin.close()
            results.close()
        def minuteView(self,line):
            global user,poste
            def unchain(string):
                result=""
                if string:
                    x=len(string)            
                    for x in range(0,x):
                        if string[x] in ["'",'"']:
                            result=result+" "
                        elif string[x] in ["#"]:
                            pass
                        else:result=result+string[x]
                return result


            def chain(string):
                results=""
                if string:
                    x=len(string)            
                    for x in range(0,x):
                        if string[x]in ["\\"]:results=results+string[x]+string[x]
                        else:results=results+string[x]
                return results
            Txzorbl={}
            final={}
            ses=0
            p=0
            Txzorbl[p]=""
            ln=len(line)
            for x in range(0,ln):
                char=line[x:x+1]
                if char=="#":
                    p+=1
                    Txzorbl[p]=""
                else:
                    Txzorbl[p]=Txzorbl[p]+char
            try:
                hour=Txzorbl[1]
                dateprem=hour[0:8]
                date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
                houre=hour[9:18]
                procs=""
                chemin=""
                fen=""
                ncl=0
                datour=str(Txzorbl[1]) 
                inscript=False
                intostr="""INSERT INTO logview (date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """
                if str(Txzorbl[2])=='user_begin':
                    ses+=1
                    action=Txzorbl[2]
                    userid=Txzorbl[3]
                    final['session','debut',str(ses)]=datour
                    final['session','user',str(ses)]=Txzorbl[4]
                    final['session','userid',str(ses)]=Txzorbl[3]
                    final['session','postepid',str(ses)]=Txzorbl[5]
                    final['session','clicknombr',str(ses)]=0
                    intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"','"+str(poste['ADMINID'])+"');"
                    inscript=True
                if str(Txzorbl[2])=='user_exit':
                    action=Txzorbl[2]
                    userid=Txzorbl[3]
                    final['session','fin',str(ses)]=datour
                    final['session','user',str(ses)]=Txzorbl[4]
                    final['session','userid',str(ses)]=Txzorbl[3]
                    final['session','postepid',str(ses)]=Txzorbl[5]
                    intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"','"+str(poste['ADMINID'])+"');"
                    inscript=True
                if str(Txzorbl[2])=='minute_maid':
                    action=Txzorbl[2]
                    chemin="None"
                    try:
                        userid=Txzorbl[6]
                    except:
                        userid=0
                    try:
                        postepid=Txzorbl[7]
                    except:
                        postepid=poste['PID']
                    try:
                        procs=chain(Txzorbl[5])
                    except:
                        procs="None"
                    try:
                        ncl=0
                        fen=chain(unchain(Txzorbl[4]))
                    except:
                        fen="None"
                    try:
                        ncl=chain(unchain(Txzorbl[3]))
                    except:
                        ncl=0
                    intostr=intostr+"('"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','','','minute_maid','"+userid+"','"+postepid+"','"+str(poste['ADMINID'])+"');"
                    inscript=True 
                if str(Txzorbl[2])=='window_change-mouse':
                    action=Txzorbl[2]
                    chemin="None"
                    try:
                        userid=Txzorbl[6]
                    except:
                        userid=0
                    try:
                        postepid=Txzorbl[7]
                    except:
                        postepid=poste['PID']
                    try:
                        procs=chain(Txzorbl[5])
                    except:
                        procs="None"
                    try:
                        ncl=0
                        fen=chain(unchain(Txzorbl[4]))
                    except:
                        fen="None"
                    try:
                        ncl=chain(unchain(Txzorbl[3]))
                    except:
                        ncl=0
                    intostr=intostr+"('"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"', '','','"+str(action)+"','"+str(userid)+"','"+str(postepid)+"','"+str(poste['ADMINID'])+"');"
                    inscript=True

                if inscript==True:
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    conn.set_client_encoding('UTF8')
                    curs = conn.cursor()
##                    presult=curs.execute("SELECT action FROM logview WHERE userid='"+userid+"';")
##                    rresult=curs.fetchone()
##                    if rresult:
##                        intostr="UPDATE logview SET date='"+str(date)+"', heure='" +str(houre)+"', nomfenetre='"+ fen+"', processus='"+ procs+"', chemin='"+chemin+"', clicks='"+str(ncl)+"', client='',activite='',action='"+str(action)+"',posteid='"+str(poste['PID'])+"',final_userid='"+poste['ADMINID']+"' WHERE userid='"+str(userid)+"';"
                    result=curs.execute(intostr)
                    conn.commit()
                    curs.close()
                    conn.close()
            except:
                pass
        def Cwrite(self,string):
            global crept,XCstring,cl
            try:
                racine=XCstring.documentElement
                element =XCstring.createElement("PrsP")
                element.setAttribute('ReportLine',string)
                racine.appendChild(element)
                self.CSave()
            finally:
    ##            if str(syncro)=="True" and start==True:
                self.minuteView(string)
                cl+=1
        def run(self):
            def unchain(string):
                result=""
                if string:
                    x=len(string)            
                    for x in range(0,x):
                        if string[x] in ["'",'"']:
                            result=result+" "
                        elif string[x] in ["#"]:
                            pass
                        else:result=result+string[x]
                return result
            global cl,nombrecliq,start
            timec=time.strftime('%m/%d/%y %H:%M:%S')
            try:
                hwnd = win32gui.GetForegroundWindow()
                # we want the desktop window
                objid = pyAA.Constants.OBJID_WINDOW
                # get the object
                ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
                pr= ao.GetProcessAndThreadID()
                p = psutil.Process(pr[0])
                processactif=p.exe
    ##            processes = win32process.EnumProcesses()
    ##    ##        c=wmi.WMI()0000
    ##            p=0
    ##    ##        for t in range(0,prs):
    ##    ##            Trmbl=True
    ##    ##            for pid in processes:
    ##    ##                try:
    ##    ##                    if pprocess[t]==pid :Trmbl=False
    ##    ##                except:
    ##    ##                    pass
    ##    ##            if Trmbl==True:
    ##    ##                timec=time.strftime('%m/%d/%y %H:%M:%S')
    ##    ##                resac='#*#'+str(timec)+'\t'+'process end'+'\t'+pprocess['n',t]+'#**#'+'\n'
    ##    ##                self.Twrite(resac)
    ##            for pid in processes:
    ##    ##       
    ##    ##            pprocess[p]=pid
    ##    ##            handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
    ##    ##            pprocess['n',p]=win32process.GetModuleFileNameEx(handle, 0)
    ##                if pid in pr:
    ##                    handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
    ##                    processactif=win32process.GetModuleFileNameEx(handle, 0)
    ####            prs=p
    ####            p+=1
            except:
                processactif="None"
            #for process in os.getpid():
            
    ##        for pid in processes:
    ##          if pid in pr:
    ##              handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
    ##              pname = win32process.GetModuleFileNameEx(handle, 0)
            
            try:
                tprocess=unchain(processactif).decode('latin-1')
            except:
                try:
                    tprocess=unchain(processactif)
                except:
                    tprocess='None'
            try:
                fen=unchain(ao.Name).decode('latin-1')
            except:
                try:
                    fen=unchain(ao.Name)
                except:
                    fen='None'
            if fen=="":fen="None"
            if tprocess=="":tprocess="None"

            #if (winame!=w.GetWindowText(hwnd) and winame!=''):
            #resac=str(timec)+'\t'+'minute maid'+'\t'+'cliques:'+str(nombrecliq)+'\t'+'keys:'+str(len(texte))+'\t'+str(winame)+'\n'
            resac=str(cl)+'#'+str(timec)+'#'+'minute_maid'+'#'+str(nombrecliq)+'#'+fen+'#'+tprocess+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'\n'
            #self.Twrite(resac)
            self.Cwrite(resac)
            nombrecliq=0
            #if ssyncro==True:self.ReadLog(computer, logType, verbose > 0)
            #changes={}
            #print 'loopminute'

    def chargeFiltres(self):
        global oscurdir,filtre,message,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,anafennamin,anafennameq

        #print "charge filtre 0"
        try:
        #if oscurdir:
            try:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
                logfile = open(chemFS,'rb')
            except:
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "need"+os.sep+"zero.gwh"
                logfile = open(chemFS,'rb')
                chemFS= oscurdir + os.sep + "wok"+os.sep+ "conf"+os.sep+"gaors.gwh"
            def Gdecrypt(outputin,result):
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=outputin.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                logfile.close()
                result.write(rep)
                return result
                        
            outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
            result = StringIO.StringIO()
            #detr=obj.decrypt(outputin.getvalue())
            Gdecrypt(outputin,result)
            #result.write(detr)
            drunk=result.getvalue()
            lou=len(drunk)
            drink=''
            #print repr(drunk)
            for c in range(0,lou):
                try:
                    if drunk[c:c+7]=='</PrsP>':
                        drink=drink+'</PrsP>'
                        break
                    else:drink=drink+drunk[c]
                except:
                    pass
            #print repr(drink) ,filtre,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,anafennamin,anafennameq

            xim=xml.dom.minidom.parseString(drink)
            logfile.close()
            unem = xim.getElementsByTagName('FILTRE')
            x=1
            xappi=1
            xafpi=1
            xappe=1
            xafpe=1
            xapne=1
            xafne=1
            xalfne=1
            xapni=1
            xafni=1
            xalfni=1
            
            #print 'charge filtre'

            filtre['nombre']=0
            for unam in unem:
                filtre['Libelle',x]=unam.getAttribute('Libelle').encode('latin-1')
                filtre['nombre']=x
                filtre['Contenant',x]=unam.getAttribute('Contenant').encode('latin-1')
                filtre['Propriete',x]=unam.getAttribute('Propriete').encode('latin-1')
                filtre['Contenu',x]=unam.getAttribute('Contenu').encode('latin-1')
                filtre['Client',x]=unam.getAttribute('Client').encode('latin-1')
                filtre['Prestation',x]=unam.getAttribute('Prestation').encode('latin-1')
                filtre['Prestationid',x]=unam.getAttribute('Prestationid').encode('latin-1')
                filtre["checked",x]=False
                #print filtre['Contenant',x]
                if filtre['Contenant',x]=="Le chemin du processus":
                    if filtre['Propriete',x]=="est égal à":
                        anaprocspathin['contenu',xappi]=filtre['Contenu',x]
                        anaprocspathin['client',xappi]=filtre['Client',x]
                        anaprocspathin['prestation',xappi]=filtre['Prestation',x]
                        anaprocspathin['prestationid',xappi]=filtre['Prestationid',x]
                        anaprocspathin['count']=xappi
                        xappi+=1
                    elif filtre['Contenant',x]=="contient":
                        anaprocspatheq['contenu',xappe]=filtre['Contenu',x]
                        anaprocspatheq['client',xappe]=filtre['Client',x]
                        anaprocspatheq['prestation',xappe]=filtre['Prestation',x]
                        anaprocspatheq['prestationid',xappe]=filtre['Prestationid',x]
                        anaprocspatheq['count']=xappe
                        xappe+=1
                elif filtre['Contenant',x]=="Le nom du processus":
                    if filtre['Propriete',x]=="est égal à":
                        anaprocsnamin['contenu',xapni]=filtre['Contenu',x]
                        anaprocsnamin['client',xapni]=filtre['Client',x]
                        anaprocsnamin['prestation',xapni]=filtre['Prestation',x]
                        anaprocsnamin['prestationid',xapni]=filtre['Prestationid',x]
                        anaprocsnamin['count']=xapni
                        xapni+=1
                    elif filtre['Contenant',x]=="contient":
                        anaprocsnameq['contenu',xapne]=filtre['Contenu',x]
                        anaprocsnameq['client',xapne]=filtre['Client',x]
                        anaprocsnameq['prestation',xapne]=filtre['Prestation',x]
                        anaprocsnameq['prestationid',xapne]=filtre['Prestationid',x]
                        anaprocsnameq['count']=xapne
                        xapne+=1
                elif filtre['Contenant',x]=="Le chemin du fichier":
                    if filtre['Propriete',x]=="est égal à":
                        anaficpathin['contenu',xafpi]=filtre['Contenu',x]
                        anaficpathin['client',xapfi]=filtre['Client',x]
                        anaficpathin['prestation',xafpi]=filtre['Prestation',x]
                        anaficpathin['prestationid',xafpi]=filtre['Prestationid',x]
                        anaficpathin['count']=xafpi
                        xafpi+=1
                    elif filtre['Propriete',x]=="contient":
                        anaficpatheq['contenu',xafpe]=filtre['Contenu',x]
                        anaficpatheq['client',xafpe]=filtre['Client',x]
                        anaficpatheq['prestation',xafpe]=filtre['Prestation',x]
                        anaficpatheq['prestationid',xafpe]=filtre['Prestationid',x]
                        anaficpatheq['count']=xafpe
                        xafpe+=1
                elif filtre['Contenant',x]=="Le nom du fichier":
                    if filtre['Propriete',x]=="est égal à":
                        anaficnamin['contenu',xafni]=filtre['Contenu',x]
                        anaficnamin['client',xafni]=filtre['Client',x]
                        anaficnamin['prestation',xafni]=filtre['Prestation',x]
                        anaficnamin['prestationid',xafni]=filtre['Prestationid',x]
                        anaficnamin['count']=xafni
                        xafni+=1
                    elif filtre['Propriete',x]=="contient":
                        anaficnameq['contenu',xafne]=filtre['Contenu',x]
                        anaficnameq['client',xafne]=filtre['Client',x]
                        anaficnameq['prestation',xafne]=filtre['Prestation',x]
                        anaficnameq['prestationid',xafne]=filtre['Prestationid',x]
                        anaficnameq['count']=xafne
                        xafne+=1
                elif filtre['Contenant',x]=="Le libellé de la fenêtre":
                    #print 'libelle de la fenetre'
                    if filtre['Propriete',x]=="est égal à":
                        anafennamin['contenu',xalfni]=filtre['Contenu',x]
                        anafennamin['client',xalfni]=filtre['Client',x]
                        anafennamin['prestation',xalfni]=filtre['Prestation',x]
                        anafennamin['prestationid',xalfni]=filtre['Prestationid',x]
                        anafennamin['count']=xalfni
                        xalfni+=1
                    elif filtre['Propriete',x]=="contient":
                        #print 'libelle de la fenetre contient',filtre['Contenu',x]
                        anafennameq['contenu',xalfne]=filtre['Contenu',x]
                        anafennameq['client',xalfne]=filtre['Client',x]
                        anafennameq['prestation',xalfne]=filtre['Prestation',x]
                        anafennameq['prestationid',xalfne]=filtre['Prestationid',x]
                        anafennameq['count']=xalfne
                        xalfne+=1
                x+=1
        except:
            print "Erreur dans le chargement des filtres"



#analyseProcessus(procs),analyseLibelle(libelle),analyseFichier(fichier)






            
    def OnClose(self, event):
        self.tskic.Destroy()
        self.Destroy()


    def SetNoteShape(self, *event):
        #region=wx.RegionFromBitmapColour(self.bitmap,'#000000',0)
        region = wx.RegionFromBitmap(self.bitmap)
        self.hasShape=self.SetShape(region)
        
    def OnKey(self,event):
        global powa
        powa=event.GetString()

    def OnClicked(self, event):
        #print 'event reached frame class'
        event.Skip()

    def Draw(self):
        global pgb
        self.dc.SetFont(self.font)
        self.dc.SetTextForeground('WHITE')
        pgb=wx.Gauge(self, -1 ,pos=(15,12),size=(188,21))
        pgb.Hide()
        self.dc.display=wx.TextCtrl(self,-1,style= wx.TE_PASSWORD,pos=(60,120))
        self.dc.message=wx.TextCtrl(self,wx.ID_ANY,'',pos=(15,12),size=(188,21))
        self.dc.message.SetBackgroundColour('#EAEAE9')
        
        #self.dc.nkey=wx.TextCtrl(self,wx.ID_ANY,'',pos=(20,39),size=(180,20))
        self.dc.display.CanPaste()
        self.dc.display.SetEditable(True)
        self.dc.message.SetValue(unicode(mes))
        self.dc.message.SetEditable(False)

        #self.dc.nkey.SetValue("CLEF DACTIVATION")#EAEAE9
        self.dc.display.Bind(wx.EVT_TEXT, self.OnKey)

    def OnPaint(self, event):
        global timerD,analyse,ssyncro
        self.verifyConfig()
        wx.BufferedPaintDC(self,self.bmp)
        #self.Draw()
        #self.verifyConfig()
        if analyse==True:self.chargeFiltres()
        #if ssyncro==True:self.chargeDossier()
        #timerD.Start(milliseconds=30000, oneShot=False)
        event.Skip()

    def OnDraw(self):
##        wx.BufferedDC(wx.ClientDC(self),self.bmp)
        self.Draw()
        
    class minuteView(Thread):
        global user,poste
        def __init__(self,string):
            Thread.__init__(self)
            self.setDaemon(1)
            self.line=string
            self.start()
        def run(self):
            global user,poste
            def unchain(string):
                result=""
                if string:
                    x=len(string)            
                    for x in range(0,x):
                        if string[x] in ["'",'"']:
                            result=result+" "
                        elif string[x] in ["#"]:
                            pass
                        else:result=result+string[x]
                return result


            def chain(string):
                results=""
                if string:
                    x=len(string)            
                    for x in range(0,x):
                        if string[x]in ["\\"]:results=results+string[x]+string[x]
                        else:results=results+string[x]
                return results
            Txzorbl={}
            final={}
            ses=0
            p=0
            Txzorbl[p]=""
            ln=len(self.line)
            for x in range(0,ln):
                char=self.line[x:x+1]
                if char=="#":
                    p+=1
                    Txzorbl[p]=""
                else:
                    Txzorbl[p]=Txzorbl[p]+char
            try:
                hour=Txzorbl[1]
                dateprem=hour[0:8]
                date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
                houre=hour[9:18]
                procs=""
                chemin=""
                fen=""
                ncl=0
                datour=str(Txzorbl[1]) 
                inscript=False
                intostr="""INSERT INTO logview (date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """
                if str(Txzorbl[2])=='user_begin':
                    ses+=1
                    action=Txzorbl[2]
                    userid=Txzorbl[3]
                    final['session','debut',str(ses)]=datour
                    final['session','user',str(ses)]=Txzorbl[4]
                    final['session','userid',str(ses)]=Txzorbl[3]
                    final['session','postepid',str(ses)]=Txzorbl[5]
                    final['session','clicknombr',str(ses)]=0
                    intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"','"+str(poste['ADMINID'])+"');"
                    inscript=True
                if str(Txzorbl[2])=='user_exit':
                    action=Txzorbl[2]
                    userid=Txzorbl[3]
                    final['session','fin',str(ses)]=datour
                    final['session','user',str(ses)]=Txzorbl[4]
                    final['session','userid',str(ses)]=Txzorbl[3]
                    final['session','postepid',str(ses)]=Txzorbl[5]
                    intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"','"+str(poste['ADMINID'])+"');"
                    inscript=True
                if str(Txzorbl[2])=='minute_maid':
                    action=Txzorbl[2]
                    chemin="None"
                    try:
                        userid=Txzorbl[6]
                    except:
                        userid=0
                    try:
                        postepid=Txzorbl[7]
                    except:
                        postepid=poste['PID']
                    try:
                        procs=chain(Txzorbl[5])
                    except:
                        procs="None"
                    try:
                        ncl=0
                        fen=chain(unchain(Txzorbl[4]))
                    except:
                        fen="None"
                    try:
                        ncl=chain(unchain(Txzorbl[3]))
                    except:
                        ncl=0
                    intostr=intostr+"('"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','','','minute_maid','"+userid+"','"+postepid+"','"+str(poste['ADMINID'])+"');"
                    inscript=True 
                if str(Txzorbl[2])=='window_change-mouse':
                    action=Txzorbl[2]
                    chemin="None"
                    try:
                        userid=Txzorbl[6]
                    except:
                        userid=0
                    try:
                        postepid=Txzorbl[7]
                    except:
                        postepid=poste['PID']
                    try:
                        procs=chain(Txzorbl[5])
                    except:
                        procs="None"
                    try:
                        ncl=0
                        fen=chain(unchain(Txzorbl[4]))
                    except:
                        fen="None"
                    try:
                        ncl=chain(unchain(Txzorbl[3]))
                    except:
                        ncl=0
                    intostr=intostr+"('"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"', '','','"+str(action)+"','"+str(userid)+"','"+str(postepid)+"','"+str(poste['ADMINID'])+"');"
                    inscript=True

                if inscript==True:
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    conn.set_client_encoding('UTF8')
                    curs = conn.cursor()
##                    presult=curs.execute("SELECT action FROM logview WHERE userid='"+userid+"';")
##                    rresult=curs.fetchone()
##                    if rresult:
##                        intostr="UPDATE logview SET date='"+str(date)+"', heure='" +str(houre)+"', nomfenetre='"+ fen+"', processus='"+ procs+"', chemin='"+chemin+"', clicks='"+str(ncl)+"', client='',activite='',action='"+str(action)+"',posteid='"+str(poste['PID'])+"',final_userid='"+poste['ADMINID']+"' WHERE userid='"+str(userid)+"';"
                    result=curs.execute(intostr)
                    conn.commit()
                    curs.close()
                    conn.close()
            except:
                pass
    class synchro(Thread):
        global issyncro,pgb,anafennamin,anafennameq,anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,anaficpathin,anaficpatheq,anaficnamin,anaficnameq,fanal,analyse,mes,listeclient,listeactivite
        def __init__(self):
            Thread.__init__(self)
            self.setDaemon(1)
            self.start()
        def formatFanal(self):
            global fanal
            fanal['client']="None"
            fanal['prestation']="None"

        def analyseLibelle(self,libelle):
            global anafennamin,anafennameq,fanal,listeclient,listeactivite
            def unchain(nstring):
                try:
                    t=len(nstring)
                    result=""
                    string=nstring.decode('latin-1').encode('latin-1')
                    for x in range(0,t):
                        if string[x] in ['é','è','ê']:
                            result=result+'e'
                        elif string[x] in ['î','ï']:
                            result=result+'i'
                        elif string[x] in ['â','ä','à']:
                            result=result+'a'
                        elif string[x] in ['ô','ö']:
                            result=result+'o'
                        else:result=result+string[x]
                    return result
                except:
                    return nstring
            
            for x in range(1,anafennamin['count']+1):
                if unchain(anafennamin['contenu',x]).upper()==unchain(libelle).upper():
                    if anafennamin['client',x]!='non défini':
                        fanal['client']=anafennamin['client',x]
                    if anafennamin['prestation',x]!='non défini':
                        fanal['prestation']=anafennamin['prestationid',x]
                if anafennamin['contenu',x]=='Le nom du client' and anafennamin['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() ==unchain(libelle).upper():
                            fanal['client']=listeclient[u]
                if anafennamin['contenu',x]=='Le nom de la prestation' and anafennamin['client',x]=='La prestation en question':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() ==unchain(libelle).upper():
                            fanal['prestation']=listeactivite[u,'id']

            for x in range(1,anafennameq['count']+1):
##                print unchain(anafennameq['contenu',x]).upper()
##                print unchain(libelle).upper()
                if unchain(anafennameq['contenu',x]).upper() in unchain(libelle).upper():
                    if anafennameq['client',x]!='non défini':
                        fanal['client']=anafennameq['client',x]
                    if anafennameq['prestation',x]!='non défini':
                        fanal['prestation']=anafennameq['prestationid',x]
                if anafennameq['contenu',x]=='Le nom du client' and anafennameq['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(libelle).upper():
                            fanal['client']=listeclient[u]
                if anafennameq['contenu',x]=='Le nom de la prestation' and anafennameq['client',x]=='La prestation en question':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(libelle).upper():
                            fanal['prestation']=listeactivite[u,'id']
        def chargeDonnees(self):
            global listeclient,listeactivite
            try:
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
                fft=open(TchemFSF, mode ='rb')
                output = StringIO.StringIO(fft.read())
                decoutput=StringIO.StringIO()
                #output.write(fft.read())
                fft.close()
                def Gdecrypt(output,decoutput):
                    global jak
                    xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                    chunksize=(64*1024)
                    rep=''
                    while True:
                        chunk=''
                        chunk=output.read(n=chunksize)
                        if len(chunk)==0:
                            break
                        elif len(chunk)%16!=0:
                            chunk += ' ' * (16-len(chunk) % 16 )
                        rep=rep+xdecryptor.decrypt(chunk)
                    decoutput.write(rep)
                    return decoutput
     
                Gdecrypt(output,decoutput)
                lines={}
                lines = decoutput.getvalue()
                #print 'lines-'+repr(lines)
                #lo=len(lines)
                #lines = decoutput.readlines()
                #print decoutput.getvalue()
                p=0
                poste={}
                presta={}
                l=0
                poste["PID"]=""
                poste["ID"]=""
                poste["posteNAME"]=""
                poste["Date"]=""
                poste["GUID"]=""
                poste["ADMINID"]=""
                T=False
                for char in lines:
                    if char=='\t':
                        p+=1
                        continue
                    if char=='\n':
                        break
                    if p==0 and l==0:poste["PID"]=poste["PID"]+char
                    if p==1 and l==0:poste["ID"]=poste["ID"]+char
                    if p==2 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                    if p==3 and l==0:poste["Date"]=poste["Date"]+char
                    if p==4 and l==0:poste["GUID"]=poste["GUID"]+char
                    if p==5 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
                if poste["ADMINID"]!="":    
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    result=curs.execute("SELECT nomsoc FROM clients WHERE idadmin='"+str(poste["ADMINID"])+"';" )
                    result=curs.fetchall()
                    x=0
                    if result:
                        for chain in result:
                            Tclient=""
                            for char in chain:
                                Tclient=Tclient+str(char)
                            listeclient[x]=Tclient
                            listeclient['nombre']=x
                            x+=1
                    presult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='0';")
                    presult=curs.fetchall()
                    presta['1','count']=0
                    presta['2','count']=0
                    presta['2','count']=0
                    x=0
                    if presult:
                        u=1
                        for pchain in presult:
                            #print chain
                            p=0
                            T0presta=""
                            T0idpresta=""
                            for pchar in pchain:
                                if p==0:T0presta=T0presta+str(pchar)
                                if p==1:T0idpresta=T0idpresta+str(pchar)
                                p+=1
                            listeactivite[x,'prestation']=T0presta
                            listeactivite[x,'id']=T0idpresta
                            listeactivite['nombre']=x
                            x+=1
                            presta[u,'0','0','label']=T0presta
                            presta[u,'0','0','id']=T0idpresta
                            presta['1','count']=u
                            ppresult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='1' AND mother='"+str(T0idpresta)+"';" )
                            ppresult=curs.fetchall()
                            if ppresult:
                                v=1
                                for ppchain in ppresult:
                                    #print chain
                                    pp=0
                                    T1presta=""
                                    T1idpresta=""
                                    for ppchar in ppchain:
                                        if pp==0:T1presta=T1presta+str(ppchar)
                                        if pp==1:T1idpresta=T1idpresta+str(ppchar)
                                        pp+=1
                                    listeactivite[x,'prestation']=T1presta
                                    listeactivite[x,'id']=T1idpresta
                                    listeactivite['nombre']=x
                                    x+=1
                                    presta[u,v,'0','label']='  --  '+str(T1presta).decode('utf-8')
                                    presta[u,v,'0','id']=T1idpresta
                                    presta['2','count']=v
                                    pppresult=curs.execute("SELECT libel,idpres FROM prestations WHERE idadmin='"+str(poste["ADMINID"])+"' AND rang='2' AND mother='"+str(T1idpresta)+"';" )
                                    pppresult=curs.fetchall()
                                    if pppresult:
                                        w=1
                                        for pppchain in pppresult:
                                            #print chain
                                            ppp=0
                                            T2presta=""
                                            T2idpresta=""
                                            for pppchar in pppchain:
                                                if ppp==0:T2presta=T2presta+str(pppchar)
                                                if ppp==1:T2idpresta=T2idpresta+str(pppchar)
                                                ppp+=1
                                            listeactivite[x,'prestation']=T2presta
                                            listeactivite[x,'id']=T2idpresta
                                            listeactivite['nombre']=x
                                            x+=1
                                            presta[u,v,w,'label']='  --  --  '+str(T2presta).decode('utf-8')
                                            presta[u,v,w,'id']=T2idpresta
                                            presta['3','count']=w
                
                                            w+=1            
                                    v+=1
                            u+=1

                    curs.close()
                    conn.close()
                else:
                    message="erreur : Faites le wizard avant"
            except:
                message="Connection internet requise"
        def analyseProcessus(self,procs):
            global anaprocspathin,anaprocspatheq,anaprocsnamin,anaprocsnameq,fanal,listeclient,listeactivite
            def unchain(nstring):
                try:
                    t=len(nstring)
                    result=""
                    string=nstring.decode('latin-1').encode('latin-1')
                    for x in range(0,t):
                        if string[x] in ['é','è','ê']:
                            result=result+'e'
                        elif string[x] in ['î','ï']:
                            result=result+'i'
                        elif string[x] in ['â','ä','à']:
                            result=result+'a'
                        elif string[x] in ['ô','ö']:
                            result=result+'o'
                        else:result=result+string[x]
                    return result
                except:
                    return nstring
            path=procs
            d=len(path)
            processpath=''
            processfile=''
            u=d
            for x in range(1,d+1):
                b=int(d)-int(x)
                f=b
                f+=1
                if path[b:f]=='\\':
                    Trmbl=True
                    u=int(d)-int(x)
                    break
                processfile=processfile+path[b:f]
            processpath=path[0:u]   
            for x in range(1,anaprocspathin['count']+1):
                if unchain(anaprocspathin['contenu',x]).upper()==unchain(processpath).upper():
                    if anaprocspathin['client',x]!='non défini':
                        fanal['client']=anaprocspathin['client',x]
                    if anaprocspathin['prestation',x]!='non défini':
                        fanal['prestation']=anaprocspathin['prestationid',x]
                if anaprocspathin['contenu',x]=='Le nom du client' and anaprocspathin['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(processpath).upper()==unchain(listeclient[u]).upper():
                            fanal['client']=listeclient[u]
                if anaprocspathin['contenu',x]=='Le nom de la prestation' and anaprocspathin['client',x]=='La prestation en question':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(processpath).upper()==unchain(listeactivite[u,'prestation']).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaprocspatheq['count']+1):
                if unchain(anaprocspatheq['contenu',x]).upper() in unchain(processpath).upper():
                    if anaprocspatheq['client',x]!='non défini':
                        fanal['client']=anaprocspatheq['client',x]
                    if anaprocspatheq['prestation',x]!='non défini':
                        fanal['prestation']=anaprocspatheq['prestationid',x]
                if anaprocspatheq['contenu',x]=='Le nom du client' and anaprocspatheq['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(processpath).upper():
                            fanal['client']=listeclient[u]
                if anaprocspatheq['contenu',x]=='Le nom de la prestation' and anaprocspatheq['client',x]=='La prestation en question':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(processpath).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaprocsnamin['count']+1):
                if unchain(anaprocsnamin['contenu',x]).upper()==unchain(processfile).upper():
                    if anaprocsnamin['client',x]!='non défini':
                        fanal['client']=anaprocsnamin['client',x]
                    if anaprocsnamin['prestation',x]!='non défini':
                        fanal['prestation']=anaprocsnamin['prestationid',x]
                if anaprocsnamin['contenu',x]=='Le nom du client' and anaprocsnamin['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() ==unchain(processfile).upper():
                            fanal['client']=listeclient[u]
                if anaprocsnamin['contenu',x]=='Le nom de la prestation' and anaprocsnamin['client',x]=='La prestation en question':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() == unchain(processfile).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaprocsnameq['count']+1):
                if unchain(anaprocsnameq['contenu',x]).upper() in unchain(processfile).upper():
                    if anaprocsnameq['client',x]!='non défini':
                        fanal['client']=anaprocsnameq['client',x]
                    if anaprocsnameq['prestation',x]!='non défini':
                        fanal['prestation']=anaprocsnameq['prestationid',x]
                if anaprocsnameq['contenu',x]=='Le nom du client' and anaprocsnameq['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(processfile).upper():
                            fanal['client']=listeclient[u]
                if anaprocsnameq['contenu',x]=='Le nom de la prestation' and anaprocsnameq['client',x]=='La prestation en question':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(processfile).upper():
                            fanal['prestation']=listeactivite[u,'id']
        def analyseFichier(self,fichier):
            global anaficpathin,anaficpatheq,anaficnamin,anaficnameq,fanal,listeclient,listeactivite
            def unchain(nstring):
                try:
                    t=len(nstring)
                    result=""
                    string=nstring.decode('latin-1').encode('latin-1')
                    for x in range(0,t):
                        if string[x] in ['é','è','ê']:
                            result=result+'e'
                        elif string[x] in ['î','ï']:
                            result=result+'i'
                        elif string[x] in ['â','ä','à']:
                            result=result+'a'
                        elif string[x] in ['ô','ö']:
                            result=result+'o'
                        else:result=result+string[x]
                    return result
                except:
                    return nstring
            d=len(fichier)
            filepath=''
            filefile=''
            u=d
            for x in range(1,d+1):
                deb=int(d)-int(x)
                fin=deb
                fin+=1
                if fichier[deb:fin]=='\\':
                    Trmbl=True
                    u=int(d)-int(x)
                    break
                filefile=filefile+fichier[deb:fin]
            filepath=fichier[0:u] 
            for x in range(1,anaficpathin['count']+1):
                if unchain(anaficpathin['contenu',x]).upper()==unchain(filepath).upper():
                    if anaficpathin['client',x]!='non défini':
                        fanal['client']=anaficpathin['client',x]
                    if anaficpathin['prestation',x]!='non défini':
                        fanal['prestation']=anaficpathin['prestationid',x]
                if anaficpathin['contenu',x]=='Le nom du client' and anaficpathin['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() == unchain(filepath).upper():
                            fanal['client']=listeclient[u]
                if anaficpathin['contenu',x]=='Le nom de la prestation' and anaficpathin['client',x]=='La prestation en question':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() == unchain(filepath).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaficpatheq['count']+1):
                if unchain(anaficpatheq['contenu',x]).upper() in unchain(filepath).upper():
                    if anaficpatheq['client',x]!='non défini':
                        fanal['client']=anaficpatheq['client',x]
                    if anaficpatheq['prestation',x]!='non défini':
                        fanal['prestation']=anaficpatheq['prestationid',x]
                if anaficpatheq['contenu',x]=='Le nom du client' and anaficpatheq['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(filepath).upper():
                            fanal['client']=listeclient[u]
                if anaficpatheq['contenu',x]=='Le nom de la prestation' and anaficpatheq['client',x]=='La prestation en question':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(filepath).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaficnamin['count']+1):
                if unchain(anaficnamin['contenu',x]).upper()==unchain(filefile).upper():
                    if anaficnamin['client',x]!='non défini':
                        fanal['client']=anaficnamin['client',x]
                    if anaficnamin['prestation',x]!='non défini':
                        fanal['prestation']=anaficnamin['prestationid',x]
                if anaficnamin['contenu',x]=='Le nom du client' and anaficnamin['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() == unchain(filefile).upper():
                            fanal['client']=listeclient[u]
                if anaficnamin['contenu',x]=='Le nom de la prestation' and anaficnamin['client',x]=='La prestation en question':
                    for u in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(filefile).upper():
                            fanal['prestation']=listeactivite[u,'id']
            for x in range(1,anaficnameq['count']+1):
                if unchain(anaficnameq['contenu',x]).upper() == unchain(filefile).upper():
                    if anaficnameq['client',x]!='non défini':
                        fanal['client']=anaficnameq['client',x]
                    if anaficnameq['prestation',x]!='non défini':
                        fanal['prestation']=anaficnameq['prestationid',x]
                if anaficnameq['contenu',x]=='Le nom du client' and anaficnameq['client',x]=='Le client en question':
                    for u in range(0,listeclient['nombre']):
                        if unchain(listeclient[u]).upper() in unchain(filefile).upper():
                            fanal['client']=listeclient[u]
                if anaficnameq['contenu',x]=='Le nom de la prestation' and anaficnameq['client',x]=='La prestation en question':
                    for x in range(0,listeactivite['nombre']):
                        if unchain(listeactivite[u,'prestation']).upper() in unchain(filefile).upper():
                            fanal['prestation']=listeactivite[u,'id']
        def run(self):
            global fanal,analyse,mes,pgb,issyncro
            if analyse==True:
                self.chargeDonnees()
            def FicExport(chemr,fic):
                global obj

                tze=0
                rrept=chem
                logfile = open(rrept, mode ='rb')
                def Gdecrypt(outputin,result):
                    xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                    chunksize=(64*1024)
                    rep=''
                    while True:
                        chunk=''
                        chunk=outputin.read(n=chunksize)
                        if len(chunk)==0:
                            break
                        elif len(chunk)%16!=0:
                            chunk += ' ' * (16-len(chunk) % 16 )
                        rep=rep+xdecryptor.decrypt(chunk)
                    logfile.close()
                    result.write(rep)
                    return result
                            
                outputin = StringIO.StringIO(logfile.read())
    ##                        outputin.write(logfile.read())
                result = StringIO.StringIO()
                #detr=obj.decrypt(outputin.getvalue())
                Gdecrypt(outputin,result)
                #result.write(detr)
                drunk=result.getvalue()
                lou=len(drunk)
                drink=''
                for c in range(0,lou):
                    try:
                        if drunk[c:c+7]=='</PrsP>':
                            drink=drink+'</PrsP>'
                            break
                        else:drink=drink+drunk[c]
                    except:
                        pass
                return drink

            def unchain(string):
                result=""
                if string:
                    x=len(string)            
                    for x in range(0,x):
                        if string[x] in ["'",'"']:
                            result=result+" "
                        elif string[x] in ["#"]:
                            pass
                        else:result=result+string[x]
                return result

            def tunchain(string):
                result=""
                if string:
                    x=len(string)            
                    for x in range(0,x):
                        if string[x] in ["'",'"']:
                            pass
                        elif string[x] in ["#"," "]:
                            pass
                        else:result=result+string[x]
                return result

            def chain(string):
                results=""
                if string:
                    x=len(string)            
                    for x in range(0,x):
                        if string[x]in ["\\"]:results=results+string[x]+string[x]
                        else:results=results+string[x]
                return results
            def intFormat(string):
                for char in string:
                    if char not in['0','1','2','3','4','5','6','7','8','9']:
                        return '0'
                return string
                #self.dc.DrawBitmap(self.syncf, 51, 168, True)

            #self.dc.DrawBitmap(self.onsync, 49, 168, True)
            issyncro=True
            conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
            conn = psycopg2.connect(conn_string)
            curs = conn.cursor()
            timec=time.strftime('%m/%d/%y %H:%M:%S')
            hour=timec
            dateprem=hour[0:8]
            date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
            intostr="SELECT nomfichier, line FROM logmaj where posteid='"+poste["ID"]+"' and type='full' ORDER BY datemaj ASC;"
            presult=curs.execute(str(intostr))
            presult=curs.fetchall()
            u=0
            p=0
            maj={}
            full=False
            for chains in presult:
                #print chain
                u+=1
                full=True
                maj['fichier',u]=""
                maj['line',u]=""
                maj['type',u]="full"
                for char in chains:
                    #print 'ficline='+str(char) + 'p='+str(u)
                    if p==0:maj['fichier',u]=maj['fichier',u]+str(char)
                    if p==1: maj['line',u]=maj['line',u]+str(char)
                    p+=1
                p=0
            pintostr="SELECT nomfichier, line FROM logmaj where posteid='"+poste["ID"]+"' and type='condensed' ORDER BY datemaj ASC;"
            ppresult=curs.execute(str(pintostr))
            ppresult=curs.fetchall()
            up=u
            po=0
            cond=False
            ftinscript=False
            ctinscript=False
            for pchains in ppresult:
                #print chain
                up+=1
                cond=True
                maj['fichier',up]=""
                maj['line',up]=""
                maj['type',up]="condensed"
                for char in pchains:
                    #print 'ficline='+str(char) + 'p='+str(up)
                    if po==0:maj['fichier',up]=maj['fichier',up]+str(char)
                    if po==1: maj['line',up]=maj['line',up]+str(char)
                    po+=1
                po=0
            encdir=os.curdir+os.sep+'wok'+os.sep+'enc'
            #self.dc.message.SetValue(unicode(mes)+"-")
            g=0
            try:
                pgb.Show()
            except:
                pass
            ligne={}
            xzorbl={}
            for f in os.listdir(encdir):
                if os.path.isdir(os.path.join(encdir, f)):
                    chemr=os.path.join(encdir, f)
                    for fic in os.listdir(chemr):
                        if os.path.isfile(os.path.join(chemr, fic)):
                            #self.dc.message.SetValue(unicode(mes)+"--")
                            chem=os.path.join(chemr, fic)
                            flo=len(chem)
                            fichier=""
                            for fm in range(0,flo-4):
                                if chem[fm]==os.sep:
                                    fichier=""
                                else:
                                    fichier=fichier+chem[fm]
                            tze=1
                            rrept=chem
                            xil=len(chem)
                            if xil>13 and str(chem[xil-13:xil])=="condensed.gwh":
                                condfichier=""
                                for fm in range(0,flo-13):
                                    if chem[fm]==os.sep:
                                        condfichier=""
                                    else:
                                        condfichier=condfichier+chem[fm]
                                dfic=condfichier
##                                print 'condensed'+str(maj['fichier',up])
##                                print 'full'+str(maj['fichier',u])
                                if cond==True:
                                    lcd=len(condfichier)
                                    lfc=len(maj['fichier',up])
                                    namor=condfichier[0:8]
                                    xnamur=maj['fichier',up]
                                    namur=xnamur[0:8]
                                    xna=condfichier[8:lcd]
                                    xno=xnamur[8:lfc]
                                    if xna=='':xna=0
                                    if xno=='':xno=0
##                                    ecart=lfc-lcd
##                                    if ecart<0:
##                                        ecur=0-int(ecart)
##                                        for x in range(0,ecur):
##                                            namur=namur+"0"
##                                    if ecart>0:
##                                        for x in range(0,ecart):
##                                            namor=namor+"0"
##                                    print str(namor) +':'+ str(namur)
##                                    print str(xna) +':'+ str(xno)
                                     
                                    if int(namor) < int(namur)and str(maj['type',up])=='condensed':
                                        continue
                                    if int(namor) == int(namur)and int(xna)< int(xno) and str(maj['type',up])=='condensed':
                                        continue
                                    if str(namor)==str(namur) and int(xna)== int(xno) and str(maj['type',up])=='condensed':
                                        tze=int(maj['line',up])+1
                                    if int(namor) > int(namur)and str(maj['type',up])=='condensed':
                                        tze=1
                                    if str(namor)==str(namur) and int(xna)> int(xno) and str(maj['type',up])=='condensed':
                                        tze=1
                                        
                            elif str(chem[xil-4:xil])==".gwh":
                                dfic=fichier
                                if full==True:
                                    lcd=len(fichier)
                                    lfc=len(maj['fichier',u])
                                    namor=fichier[0:8]
                                    xnamur=maj['fichier',u]
                                    namur=xnamur[0:8]
                                    xna=fichier[8:lcd]
                                    xno=xnamur[8:lfc]
                                    if xna=='':xna=0
                                    if xno=='':xno=0
##                                    ecart=lfc-lcd
##                                    if ecart>0:
##                                        for x in range(0,ecart):
##                                            namor=namor+"0"
##                                    if ecart<0:
##                                        ecur=0-int(ecart)
##                                        for x in range(0,ecur):
##                                            namur=namur+"0"
##                                    print str(namor) +':'+ str(namur)
##                                    print str(xna) +':'+ str(xno)
                                    if int(namor) < int(namur)and str(maj['type',u])=='full':
                                        continue
                                    if int(namor) == int(namur)and int(xna)< int(xno) and str(maj['type',u])=='full':
                                        continue
                                    if str(namor)==str(namur)and int(xna)== int(xno) and str(maj['type',u])=='full':
                                        tze=int(maj['line',u])+1
                                    if int(namor) > int(namur)and str(maj['type',u])=='full':
                                        tze=1
                                    if str(namor)==str(namur)and int(xna)> int(xno) and str(maj['type',u])=='full':
                                        tze=1


                            drink=FicExport(chemr,fic)
                            #print 'drink=',str(drink)
                            try:
                                FXTCstring=xml.dom.minidom.parseString(drink)
                            except:
                                print 'fichier non parsé: '+str(fic)
                                continue
                            fstr=""
                            lines = FXTCstring.getElementsByTagName('PrsP')
                            x=0
                            lignes={}
                            for line in lines:
                                lignes[x]=line.getAttribute('ReportLine')
                                x+=1
                                #
                                                        
                            z=0
                            p=0
    ##                        ligne[z]=""
    ##                        xzorbl[p,z]=""
                            lip=len(fstr)
                            line=False
    ##                            print repr(results)
    ##                            print lip
    ##                            print '======'
                            results=fstr
                            icar=False
                            i=0
    ##                            for z in range(0,x-1):
    ##                                print repr(lignes[z])
                                #for char in lignes[z]:
                                    #print char
                            t=x-1
                            if xil>13 and chem[xil-13:xil]=="condensed.gwh":
                                tip="condensed"
                                ligne['condensed','tze']=tze
                                ligne['condensed']=dfic
                            else:
                                tip="full"
                                ligne['full','tze']=tze
                                ligne['full']=dfic
                            for r in range(0,t):
                                line = lignes[r]
                                z=r
                                p=0
                                xzorbl[g,p,z]=""
                                ln=len(line)
                                ligne[g,'tip']=tip
                                ligne[g,'tze']=tze
                                ligne[g,'z']=z
                                ligne[g,'fichier']=dfic
                                for x in range(0,ln):
                                    char=line[x:x+1]
                                    #icar=line[x:x+2]
                                    if char=="#":
                                        p+=1
                                        if p>i:i=p
                                        xzorbl[g,p,z]=""
                                    else:

                                        xzorbl[g,p,z]=xzorbl[g,p,z]+char
                                g+=1
##                            print 'fichier: ' + str(dfic)
##                            print 'tze: '+ str(tze)
##                            print 'tip: '+ str(tip)
                                
            tg=g-1
            try:
                pgb.SetRange(tg)
            except:
                pass
            for u in range(1,g):
                try:
                    pgb.SetValue(u)
                except:
                    pass
                ses=0
                fic=0
                proc=0
                procv=0
                winv=0
                fen=""
                procs=""
                chemin=""
                date=""
                houre=""
                o=0
                p=0
                q=0
                try:
                    for x in range(0,ligne[u,'z']):
                        for t in range(0,i):
                            try:
                                xzorbl[u,t,x]=xzorbl[u,t,x].strip()
                                xzorbl[u,t,x]=xzorbl[u,t,x].strip("\r\n")
                            except:
                                pass
                except:
                    pass
                try:
                    if ligne[u,'tip']=="condensed":
                        tip="condensed"
                        intostr="""INSERT INTO logcondensed (date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """

                    else:
                        tip="full"
                        intostr="""INSERT INTO logfull (date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """

                except:
                    continue
                inscript=False
                for x in range(ligne[u,'tze'],ligne[u,'z']+1):
                    #for t in range(0,i):
                    #try:
                    
                    try:
                        hour=xzorbl[u,1,x]
                    except:
                        continue
                    dateprem=hour[0:8]
                    date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
                    houre=hour[9:18]
                    datour=str(xzorbl[u,1,x]) 
                    t=len(intostr)
                    ll=intFormat(xzorbl[u,0,x])
                    if ligne[u,'tip']=="condensed":
                        ligne['condensed','ll']=ll
                    elif ligne[u,'tip']=="full":
                        ligne['full','ll']=ll
                    chemin="None"
                    procs="None"
                    fen="None"
                    if str(xzorbl[u,2,x])=='user_begin':
                        if inscript==True:intostr=intostr+",('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+xzorbl[u,3,x]+"','"+xzorbl[u,5,x]+"','"+poste["ADMINID"]+"')"
                        else:intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+xzorbl[u,3,x]+"','"+xzorbl[u,5,x]+"','"+poste["ADMINID"]+"')"
                        inscript=True
                    elif str(xzorbl[u,2,x])=='user_exit':
                        if inscript==True:intostr=intostr+",('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+xzorbl[u,3,x]+"','"+xzorbl[u,5,x]+"','"+poste["ADMINID"]+"')"
                        else:intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+xzorbl[u,3,x]+"','"+xzorbl[u,5,x]+"','"+poste["ADMINID"]+"')"
                        inscript=True
                        ses+=1
                    elif str(xzorbl[u,2,x])in ["Created","Deleted","Updated","Renamed from something","Renamed to something"]:
                        chemin=xzorbl[u,4,x]
                        userid=intFormat(tunchain(xzorbl[u,6,x]))
                        postepid=intFormat(tunchain(xzorbl[u,7,x]))
                        ncl= intFormat(unchain(xzorbl[u,3,x]))
                        procs=chain(unchain(xzorbl[u,5,x]))
                        fen="None"
                        self.formatFanal()
                        if analyse==True:
                            self.analyseFichier(chemin)
                        if inscript==True:intostr=intostr+",('"+ date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','"+xzorbl[u,2,x]+"','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"    
                        else:intostr=intostr+"('"+ date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','"+xzorbl[u,2,x]+"','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"    
                        inscript=True
                    elif str(xzorbl[u,2,x])=='minute_maid':
                        ncl= intFormat(unchain(xzorbl[u,3,x]))
                        chemin="None"
                        self.formatFanal()
                        if analyse==True:
                            self.analyseProcessus(xzorbl[u,5,x])
                            self.analyseLibelle(xzorbl[u,4,x])
                        procs=chain(unchain(xzorbl[u,5,x]))
                        fen=chain(unchain(xzorbl[u,4,x]))
                        userid=intFormat(tunchain(xzorbl[u,6,x]))
                        postepid=intFormat(tunchain(xzorbl[u,7,x]))
                        if inscript==True:intostr=intostr+",('"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"
                        else:intostr=intostr+"('"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"
                        inscript=True
                    elif str(xzorbl[u,2,x])=='window_change-mouse':
                        Trmbl=False
                        chemin="None"
                        self.formatFanal()
                        if analyse==True:
                            self.analyseProcessus(xzorbl[u,5,x])
                            self.analyseLibelle(xzorbl[u,4,x])
                        try:
                            userid=intFormat(tunchain(xzorbl[u,6,x]))
                        except:
                            userid=0
                        try:
                            postepid=intFormat(tunchain(xzorbl[u,7,x]))
                        except:
                            postepid=intFormat(poste['PID'])
                        try:
                            procs=chain(xzorbl[5,x])
                        except:
                            procs="None"
                        try:
                            ncl=0
                            fen=chain(unchain(xzorbl[u,4,x]))
                        except:
                            fen="None"
                        try:
                            ncl=intFormat(chain(unchain(xzorbl[u,3,x])))
                        except:
                            ncl=0
                        if inscript==True:intostr=intostr+",('"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"
                        else:intostr=intostr+"('"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"','"+fanal['client']+"','"+fanal['prestation']+"','log','"+userid+"','"+postepid+"','"+poste["ADMINID"]+"')"
                        inscript=True
                timec=time.strftime('%m/%d/%y %H:%M:%S')
                hour=timec
                dateprem=hour[0:8]
                date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
                intostr=intostr+";"
                #print intostr
                #print str(intostr)
                if inscript:
                    try:
                        result=curs.execute(intostr)
                        conn.commit()
                        intostr=""
                        if ligne[u,'tip']=="full":ftinscript=True
                        elif ligne[u,'tip']=="condensed":ctinscript=True
                    except:
                        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                        print "Database connection failed!\n ->%s" % (exceptionValue)
            if ftinscript:
                try:
                    tintostr="""INSERT INTO logmaj (datemaj, nomfichier, type, start,line, posteid, userid)
                            VALUES
                            """
                    tintostr=str(tintostr)+"('now()','"+str(ligne['full'])+"','full','"+str(ligne['full','tze'])+"','"+str(ligne['full','ll'])+"','"+str(poste["ID"])+"','"+str(user["ID",to])+"');"
                    result=curs.execute(str(tintostr))
                    conn.commit()
    ##                print str(tintostr)
                    #print 'logmaj tze full '+str(ligne['full','tze'])
                    tintostr=""
                except:
                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                    print "logmaj full Database connection failed!\n ->%s" % (exceptionValue)
            if ctinscript:
                try:
                    tintostr="""INSERT INTO logmaj (datemaj, nomfichier, type, start,line, posteid, userid)
                            VALUES
                            """
                    tintostr=str(tintostr)+"('now()','"+str(ligne['condensed'])+"','condensed','"+str(ligne['condensed','tze'])+"','"+str(ligne['condensed','ll'])+"','"+str(poste["ID"])+"','"+str(user["ID",to])+"');"
                    #print str(tintostr)
                    #print intostr
                    #print 'logmaj tze condensed '+ str(ligne['condensed','tze'])
                    result=curs.execute(str(tintostr))
                    conn.commit()
                    tintostr=""
                    #self.dc.message.SetValue(unicode(mes)+u'-synchronisé')
                except:
                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                    print "logmaj condensed Database connection failed!\n ->%s" % (exceptionValue)
                    print repr(tintostr)
##            print 'ctinscript '+ str(ctinscript)
##            print 'ftinscript '+ str(ftinscript)
                
            curs.close()
            conn.close()
            pgb.Hide()
            issyncro=False






    def OnLeftDown(self, event):
        global issyncro,line1,line2,line3,dusers,jak,to,fl,cl,mlogfile,mclogfile,timer,hm,texte,logfile,resac,obj,win,timec,resac,nombrecliq,processactif,start,user,poste,to,processactif,pprocess,prs,mes,rept,oscurdir,foutputin,fresult,computer,logType,verbose,user_id,poste_pid,ssyncro,dossier,watcher
        class OnMouseEventAfter(Thread):
            global dusers,jak,to,fl,cl,resac,win,nombrecliq,processactif,user,poste,prs,mes,rept,XTstring
            def __init__(self,event):
                Thread.__init__(self)
                self.setDaemon(1)
                self.event=event
                self.start()
            def TSave(self):
                global XTstring
                def Gencrypt(results,outputfile):
                    encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                    #decryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                    chunksize=(64*1024)
                    mlogfile = open(outputfile, 'wb')
                    ret=''
                    while True:
                        chunk = results.read(n=chunksize)
                        if len(chunk)==0:
                            break
                        elif len(chunk)%16!=0:
                            chunk += ' ' * (16-len(chunk) % 16 )                
                        ret=ret+chunk
                    djunky=encryptor.encrypt(ret)
                    mlogfile.write(djunky)
                    mlogfile.close()
                class TTransPak:
                    def write(self,data):
                        outputin.write(data.encode('utf-8'))
                outputin = StringIO.StringIO()
                XTstring.writexml(TTransPak(), encoding='utf-8')
                results = StringIO.StringIO(outputin.getvalue())        
                Gencrypt(results,rept)
                outputin.close()
                results.close()
                outputin = StringIO.StringIO()
                XCstring.writexml(TTransPak(), encoding='utf-8')
                results = StringIO.StringIO(outputin.getvalue())        
                Gencrypt(results,crept)
                outputin.close()
                results.close()
            def minuteView(self,line):
                global user,poste
                def unchain(string):
                    result=""
                    if string:
                        x=len(string)            
                        for x in range(0,x):
                            if string[x] in ["'",'"']:
                                result=result+" "
                            elif string[x] in ["#"]:
                                pass
                            else:result=result+string[x]
                    return result


                def chain(string):
                    results=""
                    if string:
                        x=len(string)            
                        for x in range(0,x):
                            if string[x]in ["\\"]:results=results+string[x]+string[x]
                            else:results=results+string[x]
                    return results
                Txzorbl={}
                final={}
                ses=0
                p=0
                Txzorbl[p]=""
                ln=len(line)
                for x in range(0,ln):
                    char=line[x:x+1]
                    if char=="#":
                        p+=1
                        Txzorbl[p]=""
                    else:
                        Txzorbl[p]=Txzorbl[p]+char
                try:
                    hour=Txzorbl[1]
                    dateprem=hour[0:8]
                    date='20'+dateprem[6:8]+'/'+dateprem[0:2]+'/'+dateprem[3:5]
                    houre=hour[9:18]
                    procs=""
                    chemin=""
                    fen=""
                    ncl=0
                    datour=str(Txzorbl[1]) 
                    inscript=False
                    intostr="""INSERT INTO logview (date, heure, nomfenetre, processus, chemin, clicks, client,activite,action,userid,posteid,final_userid) VALUES """
                    if str(Txzorbl[2])=='user_begin':
                        ses+=1
                        action=Txzorbl[2]
                        userid=Txzorbl[3]
                        final['session','debut',str(ses)]=datour
                        final['session','user',str(ses)]=Txzorbl[4]
                        final['session','userid',str(ses)]=Txzorbl[3]
                        final['session','postepid',str(ses)]=Txzorbl[5]
                        final['session','clicknombr',str(ses)]=0
                        intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin + "', '0', '','','debut session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"','"+str(poste['ADMINID'])+"');"
                        inscript=True
                    if str(Txzorbl[2])=='user_exit':
                        action=Txzorbl[2]
                        userid=Txzorbl[3]
                        final['session','fin',str(ses)]=datour
                        final['session','user',str(ses)]=Txzorbl[4]
                        final['session','userid',str(ses)]=Txzorbl[3]
                        final['session','postepid',str(ses)]=Txzorbl[5]
                        intostr=intostr+"('"+date+"','"+ houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '0', '','','fin session','"+final['session','userid',str(ses)]+"','"+final['session','postepid',str(ses)]+"','"+str(poste['ADMINID'])+"');"
                        inscript=True
                    if str(Txzorbl[2])=='minute_maid':
                        action=Txzorbl[2]
                        chemin="None"
                        try:
                            userid=Txzorbl[6]
                        except:
                            userid=0
                        try:
                            postepid=Txzorbl[7]
                        except:
                            postepid=poste['PID']
                        try:
                            procs=chain(Txzorbl[5])
                        except:
                            procs="None"
                        try:
                            ncl=0
                            fen=chain(unchain(Txzorbl[4]))
                        except:
                            fen="None"
                        try:
                            ncl=chain(unchain(Txzorbl[3]))
                        except:
                            ncl=0
                        intostr=intostr+"('"+date+"','" +houre+"','"+ fen+"','"+ procs+"','"+chemin+"', '"+str(ncl)+"','','','minute_maid','"+userid+"','"+postepid+"','"+str(poste['ADMINID'])+"');"
                        inscript=True 
                    if str(Txzorbl[2])=='window_change-mouse':
                        action=Txzorbl[2]
                        chemin="None"
                        try:
                            userid=Txzorbl[6]
                        except:
                            userid=0
                        try:
                            postepid=Txzorbl[7]
                        except:
                            postepid=poste['PID']
                        try:
                            procs=chain(Txzorbl[5])
                        except:
                            procs="None"
                        try:
                            ncl=0
                            fen=chain(unchain(Txzorbl[4]))
                        except:
                            fen="None"
                        try:
                            ncl=chain(unchain(Txzorbl[3]))
                        except:
                            ncl=0
                        intostr=intostr+"('"+str(date)+"','" +str(houre)+"','"+ fen+"','"+ procs+"','"+chemin+"','"+str(ncl)+"', '','','"+str(action)+"','"+str(userid)+"','"+str(postepid)+"','"+str(poste['ADMINID'])+"');"
                        inscript=True

                    if inscript==True:
                        conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                        conn = psycopg2.connect(conn_string)
                        conn.set_client_encoding('UTF8')
                        curs = conn.cursor()
##                        presult=curs.execute("SELECT action FROM logview WHERE userid='"+userid+"';")
##                        rresult=curs.fetchone()
##                        if rresult:
##                            intostr="UPDATE logview SET date='"+str(date)+"', heure='" +str(houre)+"', nomfenetre='"+ fen+"', processus='"+ procs+"', chemin='"+chemin+"', clicks='"+str(ncl)+"', client='',activite='',action='"+str(action)+"',posteid='"+str(poste['PID'])+"',final_userid='"+poste['ADMINID']+"' WHERE userid='"+str(userid)+"';"
                        result=curs.execute(intostr)
                        conn.commit()
                        curs.close()
                        conn.close()
                except:
                    pass

            def Twrite(self,string):
                global rept,XTstring,fl
                try:
                    racine=XTstring.documentElement
                    element =XTstring.createElement("PrsP")
                    element.setAttribute('ReportLine',string)
                    racine.appendChild(element)
                    self.TSave()
                finally:
                    self.minuteView(string)
            def run(self):
                global dusers,jak,to,fl,cl,resac,win,nombrecliq,processactif,user,poste,prs,mes
                def unchain(string):
                    result=""
                    if string:
                        x=len(string)     
                        for x in range(0,x):
                            if string[x] in ["'",'"']:
                                result=result+' '
                            elif string[x] in ["#"]:
                                pass
                            else:result=result+string[x]
                    return result

                #processEndLog()
    ##            if (win!=event.WindowName and win!='' and win!="None" and win!="FolderView"):
                win=self.event.WindowName
                nombrecliq=nombrecliq+1
                timec=time.strftime('%m/%d/%y %H:%M:%S')
                processactif="None"
                # called when mouse events are received
                #print 'click souris'
                #print 'Time:',time.ctime()
                #print 'WindowName:',event.WindowName
                #print 'texte:',texte
                # return True to pass the event to other handlerspy
                try:
                    hwnd = win32gui.GetForegroundWindow()
                    # we want the desktop window
                    objid = pyAA.Constants.OBJID_WINDOW
                    # get the object
                    #ao = pyAA.AccessibleObjectFromPoint(event.Position)
                    ao = pyAA.AccessibleObjectFromWindow(hwnd, objid)
                    pr= ao.GetProcessAndThreadID()
                    p = psutil.Process(pr[0])
                    processactif=p.exe
    ##                processes = win32process.EnumProcesses()
    ##        ##        c=wmi.WMI()0000
    ##                p=0
    ##    ##            for t in range(0,prs):
        ##                Trmbl=True
        ##                for pid in processes:
        ##                    try:
        ##                        if pprocess[t]==pid :Trmbl=False
        ##                    except:
        ##                        pass
        ##                if Trmbl==True:
        ##                    timec=time.strftime('%m/%d/%y %H:%M:%S')
        ##                    resac=str(fl)+'#'+str(timec)+'#'+'process_end'+'#'+pprocess['n',t]+'#'
        ##                    self.Twrite(resac)
    ##                for pid in processes:
    ##                    try:
    ####                        pprocess[p]=pid
    ####                        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
    ####                        pprocess['n',p]=win32process.GetModuleFileNameEx(handle, 0)
    ##                        if pid in pr:
    ##                            handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False, pid)
    ##                            processactif=win32process.GetModuleFileNameEx(handle, 0)
    ####                        prs=p
    ####                        p+=1
    ##                    except:
    ##                        pass
                except:
                    processactif="None"
                try:
                    tprocess=unchain(processactif).decode('latin-1')
                except:
                    try:
                        tprocess=unchain(processactif)
                    except:
                        tprocess='None'
                try:
                    fen=unchain(self.event.WindowName).decode('latin-1')
                    if fen=="":
                        try:
                            fen=unchain(ao.Name).decode('latin-1')
                        except:
                            fen="None"                    
                except:
                    try:
                        fen=unchain(ao.Name).decode('latin-1')
                    except:
                        try:
                            fen=unchain(ao.Name)
                        except:
                            fen="None"
                if fen=="":fen="None"
                if tprocess=="":tprocess="None"
                        
                resac=str(fl)+'#'+str(timec)+'#'+'window_change-mouse'+'#'+str(nombrecliq)+'#'+fen+'#'+tprocess+'#'+str(user["ID",int(to)])+'#'+str(poste["PID"])+'\n'
                fl+=1
                self.Twrite(resac)
                return True
        def OnMouseEvent(event):
            wx.CallAfter(OnMouseEventAfter, event)
        pos = event.GetPosition()
        if self.bitmapRegion.ContainsPoint(pos):
            for x in range(458,473):
                try:
                    frame=wx.FindWindowById(x)
                    if frame.IsShown():
                        frame.Close()
                except:
                    pass
            if start ==True:
                hm.UnhookMouse()
                timec=time.strftime('%m/%d/%y %H:%M:%S')
                resac=str(fl)+'#'+timec+'#'+'widget_stop'+'#'+user["ID",int(to)]+'#'+user["nom",to]+'#'+poste["PID"]+'\n'
                self.Twrite(resac)
                resac=str(cl)+'#'+timec+'#'+'widget_stop'+'#'+user["ID",int(to)]+'#'+user["nom",to]+'#'+poste["PID"]+'\n'
                self.Cwrite(resac)
    ##                mlogfile.close()
    ##                mclogfile.close()
                #thm=pyHook.HookManager
                #logfile.close()
                self.minuteSave(self)
                #minuteView(resac)
                self.minuteView(resac)
                timer.Stop()
                #timerF.Stop()
                #timerD.Stop()
            self.Close()
        elif self.reduceRegion.ContainsPoint(pos):
            for x in range(458,472):
                try:
                    frame=wx.FindWindowById(x)
                    if frame.IsShown():
                        frame.Hide()
                except:
                    pass
            self.Hide()
        elif self.syncRegion.ContainsPoint(pos):
            wx.BufferedDC(wx.ClientDC(self),self.onsync)
            if start ==True:
                if issyncro==True:
                    self.dc.message.SetValue(unicode('synchronisation en cours'))
                else:
                    self.synchro()
            else:
                mes="Vous devez d'abord vous loguer"
            
        elif self.loginRegion.ContainsPoint(pos):
    ##            self.dc.DrawBitmap(self.loginf, 112, 138, True)
    ##            self.dc.DrawBitmap(self.syncf, 51, 168, True)
##            self.dc.DrawBitmap(self.sync, 51, 168, True)
            wx.BufferedDC(wx.ClientDC(self),self.onlogin)
            #self.dc.DrawBitmap(self.onlogin, 117, 146, True)
            

            #try:  
            TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
            fft=open(TchemFSF, mode ='rb')
            output = StringIO.StringIO(fft.read())
            decoutput=StringIO.StringIO()
            #output.write(fft.read())
            fft.close()
            def Gdecrypt(output,decoutput):
                global jak
                xdecryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                chunksize=(64*1024)
                rep=''
                while True:
                    chunk=''
                    chunk=output.read(n=chunksize)
                    if len(chunk)==0:
                        break
                    elif len(chunk)%16!=0:
                        chunk += ' ' * (16-len(chunk) % 16 )
                    rep=rep+xdecryptor.decrypt(chunk)
                decoutput.write(rep)
                return decoutput
            def unchar(timestring):
                result=""
                i=0
                for char in timestring:
                    if char in ['-',' ',':']:
                        pass
                    else:
                        result=result+str(char)
                        i+=1
                    if i==8:
                        break
                return result 
            Gdecrypt(output,decoutput)
            lines={}
            lines = decoutput.getvalue()
            #print 'lines-'+repr(lines)
            #lo=len(lines)
            #lines = decoutput.readlines()
            #print decoutput.getvalue()
            p=0
            poste={}
            user={}
            l=0
            poste["PID"]=""
            poste["ID"]=""
            poste["posteNAME"]=""
            poste["Date"]=""
            poste["GUID"]=""
            poste["ADMINID"]=""
            T=False
            for char in lines:
                if char=='\t':
                    p+=1
                    continue
                if char=='\n':
                    T=True
                    p=0
                    l+=1
                    user["ID",l]=""
                    user["nom",l]=""
                    user["prenom",l]=""
                    user["login",l]=""
                    user["pass",l]=""
                    user["nombre"]=l
                    continue
                if p==0 and l==0:poste["PID"]=poste["PID"]+char
                if p==1 and l==0:poste["ID"]=poste["ID"]+char
                if p==2 and l==0:poste["posteNAME"]=poste["posteNAME"]+char
                if p==3 and l==0:poste["Date"]=poste["Date"]+char
                if p==4 and l==0:poste["GUID"]=poste["GUID"]+char
                if p==5 and l==0:poste["ADMINID"]=poste["ADMINID"]+char
                if T==True and p==0:user["ID",l]= user["ID",l]+char
                if T==True and p==1:user["nom",l]= user["nom",l]+char
                if T==True and p==2:user["prenom",l]= user["prenom",l]+char
                if T==True and p==3:user["login",l]= user["login",l]+char
                if T==True and p==4:user["pass",l]= user["pass",l]+char
##            for x in range(1,l+1):
##                print user["pass",x]
##            m = md5.new()
##            m.update(powa)
##            print poste["Date"]
##            print time.strftime('%Y-%m-%d %H:%M:%S')
            hash1=MD5.new()
##            hash1.digest_size()=16
##            hash2.digest_size()=16
            found = "not"
            if powa:
                found=False
                hash1.update(powa)
                pass2 = hash1.hexdigest()
                #print 'passé='+pass2
                for x in range(1,l+1):
    ##                pass1 = hashlib.sha1(powa).digest()
    ##                pass2 = hashlib.sha1(pass1).hexdigest()                
                    #print user["pass",x]
                    
                    if pass2==user["pass",x]:
                        user_id=user["ID",x]
                        poste_pid=poste["ID"]
                        poste["PID"]=poste["ID"]
                        to=int(x)
                        found=True
                        #print 'gagne'
            if found==False or str(found) == "not":
                if found==False:
                    mes='erreur identifiant'
                    self.dc.message.SetValue(unicode('erreur identifiant'))
                elif str(found)=="not":
                    mes='entrez votre pass'
                    self.dc.message.SetValue(unicode('entrez votre pass'))
            elif int(unchar(poste["Date"]))<int(unchar(time.strftime('%Y-%m-%d'))):
                #try:
                if poste["Date"]:
                    conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                    conn = psycopg2.connect(conn_string)
                    curs = conn.cursor()
                    query2="SELECT id,postename,datefin,activated,guid FROM postes WHERE userid='"+str(poste['ADMINID'])+"';"
                    #print query2
                    try:
                        presult=curs.execute(query2)
                        presult=curs.fetchall()                                                   
                    except:
                        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                        print "Database connection failed!\n ->%s" % (exceptionValue)
                        line3="erreur 88" 
                    if presult:
                        #print 'bingo'
                        postes={}
                        active=True
                        postes['selected']=False
                        regroot=_winreg.HKEY_LOCAL_MACHINE
                        hKey=_winreg.OpenKey(regroot,"SOFTWARE\Microsoft\Cryptography",0,_winreg.KEY_READ)
                        keyvalue, type=_winreg.QueryValueEx(hKey, "MachineGuid")
                        u=1
                        for pchain in presult:
                            postes['ID',u]=""
                            postes['posteNAME',u]=""
                            postes['dateFin',u]=""
                            postes['activated',u]=""
                            postes['guid',u]=""
                            postes['nombre']=u
                            p=0
                            for pchar in pchain:
                                #print pchar
                                if p==0:postes['ID',u]=postes['ID',u]+str(pchar)
                                if p==1:postes['posteNAME',u]=postes['posteNAME',u]+str(pchar)
                                if p==2:postes['dateFin',u]=postes['dateFin',u]+str(pchar)
                                if p==3:postes['activated',u]=postes['activated',u]+str(pchar)
                                if p==4:postes['guid',u]=postes['guid',u]+str(pchar)
                                p+=1
                            if postes['guid',u]==str(keyvalue) and postes['activated',u]=="1":
                                postes['selected']=u
                                u+=1
                            elif postes['activated',u]=="0":
                                u+=1
                        if postes['selected']:
                            if int(unchar(postes['dateFin',postes['selected']]))>int(unchar(poste["Date"])):
                                try:
                                    TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
                                    #fft=open(TchemFSF, mode ='w+')
                                except:
                                    line2='erreur ouverture fichier'
                                
                                def Gencrypt(output,TchemFSF):
                                    global jak
                                    encryptor=AES.new(str(ElChaloR[0:24]), AES.MODE_CBC,jak)
                                    chunksize=(64*1024)
                                    mlogfile = open(TchemFSF, 'wb')
                                    ret=''
                                    while True:
                                        chunk = output.read(n=chunksize)
                                        if len(chunk)==0:
                                            break
                                        elif len(chunk)%16!=0:
                                            chunk += ' ' * (16-len(chunk) % 16 )                
                                        ret=ret+chunk
                                    djunky=encryptor.encrypt(ret)
                                    mlogfile.write(djunky)
                                    mlogfile.close()
                                def Twrite(data):
                                    fft.write(data)
                                try:
                                    postehip=postes['selected']
                                    strin=poste["PID"]+'\t'+postes["ID",int(postehip)]+'\t'+postes["posteNAME",int(postehip)]+'\t'+postes["dateFin",int(postehip)]+'\t'+str(postes['guid',int(postehip)])+'\t'+poste["ADMINID"]+'\n'
                                    for x in range(1,int(user['nombre'])+1):
                                        strin=strin+user["ID",x]+'\t'+user["nom",x]+'\t'+user["prenom",x]+'\t'+user["login",x]+'\t'+user["pass",x]+'\n'
                                    #print strin
                                except:
                                    line2='dic error'
                                try:
                                    output = StringIO.StringIO(strin)
                                except:
                                    line3='string error'
                                try:
                                    Gencrypt(output,TchemFSF)
                                except:
                                    line3=line3+'-erreur encription'
                                if int(unchar(postes["dateFin",int(postehip)]))>int(unchar(time.strftime('%Y-%m-%d %H:%M:%S'))):
                                    timec=time.strftime('%m/%d/%y %H:%M:%S')
                    ##                resac='#*#'+str(timec)+'\t'+'begin'+'\n'
                    ##                self.Twrite(resac)
                    ##                self.Cwrite(resac)
                    ##                mclogfile = open(crept, mode ='w')
                    ##                mlogfile = open(rept, mode ='w')
                                    resac=str(fl)+'#'+timec+'#'+'user_begin'+'#'+user["ID",int(to)]+'#'+user["nom",int(to)]+'#'+poste["PID"]+'\n'
                                    self.Twrite(resac)
                                    resac=str(cl)+'#'+timec+'#'+'user_begin'+'#'+user["ID",int(to)]+'#'+user["nom",int(to)]+'#'+poste["PID"]+'\n'
                                    self.Cwrite(resac)
                                    hm = pyHook.HookManager()
                                    # watch for all mouse events
                                    hm.MouseLeftDown = OnMouseEvent
                                    # set the hook user["ID",to]
                                    hm.HookMouse()
                                    mes='-'+user["nom",to]+'-connecte-'
                                    #self.dc.message.SetEditable(True)
                                    self.dc.message.SetValue(unicode(mes))
                                    computer = None
                                    logType = "Security"
                                    verbose = 0
                                    #elf.dc.message.SetEditable(False)
                                    start=True
                                    if ssyncro==True:self.chargeDossier()
                                    timer.Start(milliseconds=60000, oneShot=False)
                                    #minuteView(resac)
                                    self.minuteView(resac)
                                    #timerF.Start(milliseconds=10000, oneShot=False)
                            else:
                                line1="Licence périmée."
                                line2="Demandez le renouvellement" 
                                line3="à votre administrateur."
                                try:
                                    dialogframe = wx.FindWindowById(465)
                                    dialogframe.Close()
                                    WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                                except:
                                    WizardEnd(None, 465, 'Chronos Monitor Configuration')
                        else:
                            line1="Licence périmée."
                            line2="Demandez le renouvellement" 
                            line3="à votre administrateur."
                            try:
                                dialogframe = wx.FindWindowById(465)
                                dialogframe.Close()
                                WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                            except:
                                WizardEnd(None, 465, 'Chronos Monitor Configuration') 
                                                       
##                except:
##                    line1="Licence périmée."
##                    line2="Demandez le renouvellement" 
##                    line3="à votre administrateur."
##                    try:
##                        dialogframe = wx.FindWindowById(465)
##                        dialogframe.Close()
##                        WizardEnd(None, 465, 'Chronos Monitor Configuration')            
##                    except:
##                        WizardEnd(None, 465, 'Chronos Monitor Configuration')
            else:
                timec=time.strftime('%m/%d/%y %H:%M:%S')
##                resac='#*#'+str(timec)+'\t'+'begin'+'\n'
##                self.Twrite(resac)
##                self.Cwrite(resac)
##                mclogfile = open(crept, mode ='w')
##                mlogfile = open(rept, mode ='w')
                resac=str(fl)+'#'+timec+'#'+'user_begin'+'#'+user["ID",int(to)]+'#'+user["nom",int(to)]+'#'+poste["PID"]+'\n'
                self.Twrite(resac)
                resac=str(cl)+'#'+timec+'#'+'user_begin'+'#'+user["ID",int(to)]+'#'+user["nom",int(to)]+'#'+poste["PID"]+'\n'
                self.Cwrite(resac)
                self.minuteSave(self)
                try:
                    
                    # watch for all mouse events
                    hm.MouseLeftDown = OnMouseEvent
                    # set the hook user["ID",to]
                    hm.HookMouse()
                    mes='-'+user["nom",to]+'-connecte-'
                    #self.dc.message.SetEditable(True)
                    self.dc.message.SetValue(unicode(mes))
                    #elf.dc.message.SetEditable(False)
                    start=True
                    if ssyncro==True:self.chargeDossier()
                    timer.Start(milliseconds=60000, oneShot=False)

                    self.minuteView(resac)
                    #timerF.Start(milliseconds=10000, oneShot=False)
                except:
                    
                    pass
            
                #pythoncom.PumpMessages()
##            except:
##                mes="configurez d'abord le poste"
##                self.dc.message.SetValue(unicode(mes))
        elif self.logoutRegion.ContainsPoint(pos):
##            self.dc.DrawBitmap(self.logoutf, 44, 138, True)
##            self.dc.DrawBitmap(self.syncf, 51, 168, True)
##            self.dc.DrawBitmap(self.sync, 51, 168, True)
            wx.BufferedDC(wx.ClientDC(self),self.onlogout)
            #self.dc.DrawBitmap(self.onlogout, 49, 146, True)
            if start ==True:
                hm.UnhookMouse()
                timec=time.strftime('%m/%d/%y %H:%M:%S')
                resac=str(fl)+'#'+timec+'#'+'user_exit'+'#'+user["ID",int(to)]+'#'+user["nom",to]+'#'+poste["PID"]+'\n'
                self.Twrite(resac)
                resac=str(cl)+'#'+timec+'#'+'user_exit'+'#'+user["ID",int(to)]+'#'+user["nom",to]+'#'+poste["PID"]+'\n'
                self.Cwrite(resac)
##                mlogfile.close()
##                mclogfile.close()
                #thm=pyHook.HookManager
                #logfile.close()
                self.minuteSave(self)
                self.minuteView(resac)
                timer.Stop()
                #timerF.Stop()
                #timerD.Stop()
                mes='Deconnecte'
##                for i in range(1,dossier['nombre']+1):
##                    watcher[i].kill()
                self.dc.message.SetValue(unicode(mes))
                self.dc.display.SetValue("")
                start=False
            else:
                mes="Non connecte"
                self.dc.message.SetValue(unicode(mes))
                
        elif self.optionsRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.bmp, 0, 0, True)
            #self.dc.display.Show()
            #self.dc.DrawBitmap(self.optionsf, 134, 261, True)
            #self.dc.DrawBitmap(self.onoptions, 136, 261, True)
            wx.BufferedDC(wx.ClientDC(self),self.onoptions)
            #self.dc.Show()
            try:
                TchemFSF=oscurdir+os.sep+'wok'+os.sep+'conf'+os.sep+'local.gwh'
                fft=open(TchemFSF, mode ='rb')
                fft.close()
                if start ==True:
                    try:
                        conn_string = "host='88.191.122.246' dbname='chronos-monitor.com' user='user' password='gaor867'"
                        conn = psycopg2.connect(conn_string)                        
                        curs = conn.cursor()
                        result=curs.execute("SELECT config,auto,export,password,sfiltre FROM droits_ut WHERE id='"+str(user["ID",int(to)])+"';" )
                        result=curs.fetchone()
                        u=1
                        if result:
                            active=True
                            p=0
                            dusers['config']=""
                            dusers['auto']=""
                            dusers['export']=""
                            dusers['password']=""
                            dusers['sfiltre']=""
                            for chain in result:
                                if p==0:dusers['config']=dusers['config']+str(chain)
                                if p==1:dusers['auto']=dusers['auto']+str(chain)
                                if p==2:dusers['export']=dusers['export']+str(chain)
                                if p==3:dusers['password']=dusers['password']+str(chain)
                                if p==4:dusers['sfiltre']=dusers['sfiltre']+str(chain)
                                p+=1
                            dusers['active']=True
                        if dusers['config']=="0" and dusers['auto']=="0" and dusers['export']=="0":
                            line1="Action non autorisée."
                            line2="Demandez l'autorisation" 
                            line3="à votre administrateur."
                            try:
                                dialogframe = wx.FindWindowById(465)
                                dialogframe.Close()
                                WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                            except:
                                WizardEnd(None, 465, 'Chronos Monitor Configuration')
                        else:
                            try:
                                optionsframe = wx.FindWindowById(458)
                                if optionsframe.IsShown():
                                    optionsframe.Show()
                            except:Options(None, 458, 'Chronos Monitor Options')

                    except:
                        line1="Veuillez vous connecter"
                        line2="à internet pour configurer" 
                        line3="le GWatcher."
                        try:
                            dialogframe = wx.FindWindowById(465)
                            dialogframe.Close()
                            WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                        except:
                            WizardEnd(None, 465, 'Chronos Monitor Configuration')                        
                else:
                    line1="Veuillez ouvrir"
                    line2="votre session GWatcher" 
                    line3="pour accéder à la configuration."
                    try:
                        dialogframe = wx.FindWindowById(465)
                        dialogframe.Close()
                        WizardEnd(None, 465, 'Chronos Monitor Configuration')            
                    except:
                        WizardEnd(None, 465, 'Chronos Monitor Configuration')
            except:
                try:
                    optionsframe = wx.FindWindowById(458)
                    if optionsframe.IsShown():
                        optionsframe.Show()
                except:Options(None, 458, 'Chronos Monitor Options')
                
        elif self.listeRegion.ContainsPoint(pos):
            #self.dc.DrawBitmap(self.listef, 14, 40, True)
            wx.BufferedDC(wx.ClientDC(self),self.onliste)
            #self.dc.DrawBitmap(self.onliste, 10, 40, True)
            if start ==True:
                webbrowser.open('http://www.chronosmonitor.com/vipG.php?login='+str(user["login",to])+"&pid="+str(user["pass",to]))
            else:
                mes="Vous devez d'abord vous loguer"
                self.dc.message.SetValue(unicode(mes))
        x, y = self.ClientToScreen(event.GetPosition())
        ox, oy = self.GetPosition()
        dx = x - ox
        dy = y - oy
        self.delta = ((dx, dy))


    def OnMouseMove(self, event):
        global tenter,mes
        if event.LeftIsDown()==False:
            pos = event.GetPosition()
            if self.syncRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.syncf, 51, 168, True)
                wx.BufferedDC(wx.ClientDC(self),self.oversync)
                #wx.BufferedPaintDC(self,self.oversync)
                
#                dc.DrawBitmap(self.oversync, 49, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.loginRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.loginf, 112, 138, True)
##                self.dc.DrawBitmap(self.syncf, 51, 168, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
#                wx.BufferedPaintDC(self,self.bmp)
                wx.BufferedDC(wx.ClientDC(self),self.overlogin)
                #self.dc.DrawBitmap(self.overlogin, 117, 146, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.logoutRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logoutf, 44, 138, True)
##                self.dc.DrawBitmap(self.syncf, 51, 168, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
                wx.BufferedDC(wx.ClientDC(self),self.overlogout)
                #self.dc.DrawBitmap(self.overlogout, 49, 146, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.optionsRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
                #self.dc.DrawBitmap(self.optionsf, 128, 252, True)
                wx.BufferedDC(wx.ClientDC(self),self.overoptions)
                #self.dc.DrawBitmap(self.overoptions, 132, 260, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.listeRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
                #self.dc.DrawBitmap(self.listef, 14, 40, True)
                wx.BufferedDC(wx.ClientDC(self),self.overliste)
                #self.dc.DrawBitmap(self.overliste, 10, 40, True)
                #self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.crossoverRegion.ContainsPoint(pos):
                #self.dc.DrawBitmap(self.bitmap, 0, 0, True)
                #self.dc.DrawBitmap(self.crossf, 200, 40, True)
                wx.BufferedDC(wx.ClientDC(self),self.crossover)
                #self.dc.DrawBitmap(self.crossover, 196, 44, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
##                self.dc.DrawBitmap(self.reduce, 180, 45, True)
                tenter=True
            elif self.reduceRegion.ContainsPoint(pos):
##                self.dc.DrawBitmap(self.bitmap, 0, 0, True)
##                self.dc.DrawBitmap(self.cross, 200, 40, True)
##                self.dc.DrawBitmap(self.sync, 51, 168, True)
##                self.dc.DrawBitmap(self.login, 112, 138, True)
##                self.dc.DrawBitmap(self.logout, 44, 138, True)
##                self.dc.DrawBitmap(self.options, 128, 252, True)
##                self.dc.DrawBitmap(self.liste, 14, 40, True)
                #self.dc.DrawBitmap(self.reducef, 180, 45, True)
                wx.BufferedDC(wx.ClientDC(self),self.reduceover)
                #self.dc.DrawBitmap(self.reduceover, 180, 47, True)
                tenter=True
            else:
                if tenter==True:
                    #self.dc.DrawBitmap(self.bmp, 0, 0, True)
                    wx.BufferedDC(wx.ClientDC(self),self.bmp)
                    self.dc.message.Show()
                    self.dc.message.SetValue(unicode(mes))
                    self.dc.display.Show()
##                    self.dc.DrawBitmap(self.login, 117, 146, True)
##                    self.dc.DrawBitmap(self.logout, 49, 146, True)
##                    self.dc.DrawBitmap(self.options, 132, 260, True)
##                    self.dc.DrawBitmap(self.liste, 10, 40, True)
##                    self.dc.DrawBitmap(self.reduce, 180, 47, True)
                    tenter=False

        if event.Dragging() and event.LeftIsDown():
            x, y = self.ClientToScreen(event.GetPosition())
            fp = (x - self.delta[0], y - self.delta[1])
            self.Move(fp)
        #print enter
        event.Skip()

MelChioR='GSDGJSVPIGJVGBJPOGJPJGPGJPSP11VSEGTSBSSVVDVSVDG353553BDBHYFHDJHDIHTHBYHDHYYHYDHYDD'    
ElGrandeMatadoR='HY6YYHTD8HN68DFY48HYRH74T876H4DR3H43HGGJJ8Y8TY4D34GHR8RY38FYH4348RHDRFDV5843YH4374YH874DTY38H4DY384R3D8H4DY34D3K84OU8HL45843Q84AG84AZ84RFTHDFY38JU4834FKU4K4K8ULO4Y3RY13DET463J434JR3T84J43I6U87KL4Y38937TR94R3J8448K3R864783R684786I438'
ElCondoR='4YBD3H4DERRTYTYYH834DFHY384H7HDFY384HDFY84GUH3HYF3JH4JY3O8L43H843V8FY4VD84D384H3V8UT4K3B1T3BK43F8K43I84N54V38D8FY789EY874DY1HC836168H46UI4OGM6I84FCD6T8C4X6ER46SG84TY686TY4GHVSRHY46CRY8HC6Y87468RSX4XS84SEG7BV76F8JU4IUL86OM486I4GJUV864F86DYT4C6'
ElMatadoR='HY68HYHTYN68DFY48HTYHTHYYRH74T876H4DR3H438DDSDY8TY4D34GHR8RY38FYH4348RHDR843YH4374YH874DTY38H4DY384R3D8H4DY34D3K84OU8HL45843Q84AG84AZ84RFTHDFY38JU4834FKU4K4K8ULO4Y3RY13DET463J434JR3T84J43I6U87KL4Y38937TR94R3J8448K3R864783R684786I438'
def ElBrassoR():
    global ElChaloR
    ElChaloR=MelChioR[4:6]+ElGrandeMatadoR[8:10]+ElCondoR[18:20]+ElMatadoR[11:13]+MelChioR[5:7]+ElCondoR[20:22]+ElGrandeMatadoR[25:27]+ElCondoR[28:30]+ElMatadoR[17:19]+ElGrandeMatadoR[21:23]+MelChioR[12:14]+ElMatadoR[30:32]

ElBrassoR()
USE_BUFFERED_DC = 1
reset=False
ssyncro=False
analyse=False
analysereset=False
question=False
start=False
deltatrsp=255
dinac=60
app = wx.App()
Widget(None, -1, 'Chronos Monitor')
enter=False
app.MainLoop()
