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

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

activeCards = {}

try:
    with open('people.json', 'r') as f:
        activeCards = json.load(f)
except:
    print("No people.json found")

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

    def read(self):
        global activeCards

        print("Priloz kartu")

        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
                    self.receivedNumber = 10 * self.receivedNumber + receivedDigit

                if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not self.receivedNumber == 0 )):
                    try:
                        cardPresent = False
                        for i in activeCards:
                            if activeCards[i] == self.receivedNumber:
                                cardPresent = True
                                break
                        if cardPresent == False:
                            assign=threading.Thread(target=self.assign)
                            assign.start()
                        else:
                            print("Naramek jiz zaregistrovan")
                            self.receivedNumber = 0
                            print("Priloz kartu")
                    except Exception as e: print(e)

            except KeyboardInterrupt:
                exit()
            except:
                pass

            time.sleep(0.001)

    def assign(self):
        global activeCards

        n = input("Cislo zavodnika: ")
        activeCards[str(n)] = self.receivedNumber
        with open('people.json', 'w') as f:
            f.write(json.dumps(activeCards, indent = 4))
            self.receivedNumber = 0
        print("Ulozeno, priloz kartu")

if __name__ == "__main__":
    reader = UsbCardReader()
    print("Zapis zavodniku ready")
    reader.read()