import threading
import time
import usb.core
import usb.util
import requests
import json
import datetime

DEBUG = False

if DEBUG == True:
    index = 2
else:
    index = 1
activeCards = []

TIME = 600

USB_IF      = 0 # Interface
USB_TIMEOUT = 5 # Timeout in ms
USB_VENDOR  = 0xffff # Vendor-ID:
USB_PRODUCT = 0x0035 # Product-ID

with open('people.json', 'r') as f:
    db = json.load(f)

try:
    times = {}
    with open('times.json', 'r') as f:
        times_json = json.load(f)
    for i in times_json:
        times[i] = {}
        times[i]['start'] = datetime.datetime.strptime(times_json[i]['start'],"%d/%m/%Y, %H:%M:%S")
        try:
            times[i]['end'] = datetime.datetime.strptime(times_json[i]['end'],"%d/%m/%Y, %H:%M:%S")
            times[i]['duration'] = times[i]['end'] - times[i]['start']
        except:
            print(i, "Not finished yet")
    print(times)
except Exception as e: print(e)
#except:
#    times = {}
#    times_json = {}

class UsbCardReader():
    def __init__(self, **kargs):
        # Find the HID device by vendor/product ID
        self.dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)
        # Get and store the endpoint
        self.endpoint = self.dev[0][(0,0)][0]
        if self.dev.is_kernel_driver_active(USB_IF) is True:
            self.dev.detach_kernel_driver(USB_IF)
        # Claim the device
        usb.util.claim_interface(self.dev, USB_IF)
        self.receivedNumber = 0

        cardread=threading.Thread(target=self.read)
        cardread.start()

    def read(self):
        global activeCards, db, times, times_json

        print("Waiting for card")
        receivedNumber = 0

        while True:
            control = None
            try:
                control = self.dev.read(self.endpoint.bEndpointAddress, self.endpoint.wMaxPacketSize, USB_TIMEOUT)
                if (control[2] != 40) & (control[2] != 0):
                    receivedDigit = control[2] - 29
                    if receivedDigit == 10:
                        receivedDigit = 0
                    receivedNumber = 10 * receivedNumber + receivedDigit

                if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not receivedNumber == 0 )):
                    try:
                        with open('people.json', 'r') as f:
                            db = json.load(f)
                        for i in db:
                            if db[i] == receivedNumber:
                                print("Runner:", i)
                                print(db)
                                runner_found = False
                                for j in times:
                                    if j == i:
                                        runner_found = True
                                        times[j]['end'] = datetime.datetime.now()
                                        times[j]['duration'] = times[j]['end'] - times[j]['start']
                                        times_json[j]['end'] = times[j]['end'].strftime("%d/%m/%Y, %H:%M:%S")
                                        times_json[j]['duration'] = str(times[j]['duration'])
                                if runner_found == False:
                                    times[i] = {}
                                    times[i]['start'] = datetime.datetime.now()
                                    times_json[i] = {}
                                    times_json[i]['start'] = times[i]['start'].strftime("%d/%m/%Y, %H:%M:%S")
                                with open("times.json", 'w') as f:
                                    f.write(json.dumps(times_json, indent = 4))
                                print(times)
                    except Exception as e: print(e)
                    receivedNumber = 0

            except KeyboardInterrupt:
                exit()
            except:
                pass

            time.sleep(0.001)

UsbCardReader()