from my_logger import Log
from time import sleep
import os, sys
import evdev
import subprocess
from threading import Thread
import time, datetime

log = Log("key_listener")

def call_main():
    # log.info(event)
    exec_dir = os.path.dirname(sys.argv[0])
    log.info("exec_dir: " + exec_dir)
    command = "sh {}/main.sh".format(exec_dir)
    log.info(command)
    log.info(subprocess.call(command.split()))
    
keyboard_device = None

call_main()

try:
    """
    for i in range(6):
        string_device = "/dev/input/event"+str(i)
        log.info(string_device)
        device = evdev.InputDevice(string_device)
        name_device = str(device).lower()
        log.info(device)
        if name_device.__contains__("keyboard"):
            log.info("Keyboard device detected")
            keyboard_device = device
            break
"""
    string_device = "/dev/input/event"+str(0)
    log.info(string_device)
    device = evdev.InputDevice(string_device)
    keyboard_device=device
    log.info(keyboard_device)
    for event in keyboard_device.read_loop():
        if event.type == evdev.ecodes.EV_KEY and event.value == 0 and event.code == 41:
            log.info("event_code: {}".format(event.code))
            log.info(event)
            current_time = round(time.time())
            log.info("current_time: {}".format(current_time))            
            log.info("event.sec: {}".format(event.sec))

            if (current_time - event.sec < 2):
                th = Thread(target=call_main())
                th.start()
                sleep(1)        
except Exception as e:
    log.error(log.get_line())
