import nfc
import subprocess
import datetime
import requests
import sys

time_tag = {}

def get_reader():
  devices = subprocess.check_output("lsusb")
  for i in devices.split(b'\n'):
    if str(i).__contains__("Advanced Card Systems, Ltd ACR122U"):
      bus = str(i).split(":")[0].split(" Device ")[0].split("Bus ")[1]
      device = str(i).split(":")[0].split("Device ")[1]
      return("usb:{}:{}".format(bus, device))
  sys.exit("\n\n Error: NFC reader konnte nicht erkannt werden! \n\n")  

def onTagSense(tag):
    id = int.from_bytes(tag.identifier, "big") 
    if id in time_tag and time_tag[id] > datetime.datetime.now().timestamp() - float(2):
        return False	
    else:
        time_tag[id] = datetime.datetime.now().timestamp()
        print(id)
        response = requests.get(f"http://localhost:5000/api/tag_id?id={id}")
        print(response.text)
        if response.text == "True":
          return True
        elif response.text == "False":
          return False
        else:
          print("Error: falstsche Response erhalten")
          return False
            
def main():
    device = get_reader()
    clf = nfc.ContactlessFrontend(device)
    clf.open(device)
    while True:
        print("sensing")
        clf.connect(rdwr={'on-connect': onTagSense, 'beep-on-connect': True})

main()