#!/usr/bin/env python

import os
import nfc
import time
import json
import web
import pickle
import threading

print 'Starting'

#cardusers = {'0455B36A714081':'80sSpaceMan', '091C9431':'ByronGoCard', '03B3DA80':'BlueTag','04EC364ABD3980':'RedTag'};

#json.dumps()   json.loads()

#cardusers = {
#  '0455B36A714081': {
#    'name': 'space',
#    'last_signin': 12345,
#  },
#}

#cardusers['041FBDE21A2681']['name']
#carduser.get('cardidhere', None)
#if 'cardidhere' in cardusers:



cardusers = pickle.load( open("users.p","rb") )

#cardusers['041FBDE21A2681'] = 'BlackTag'
#pickle.dump( cardusers, open("users.p","wb") )
#exit()

print ( cardusers['0455B36A714081'] )

inloop=False

global currenttag
currenttag=0
prevtag=1


##  ---   Web severy stuff --

global currentcard
currentcard = None
tag_data_timeout = 5  # 10 seconds
last_tag_read_time = 0

class MyWebserver(threading.Thread):

#  global currentcard
#  cardusers['041FBDE21A2681'] = 'BlackTag'

  def run (self):
    urls = (
      '/card/id', 'show_card_id',
      '/card/data', 'show_carduser',
#      '/users/(.*)', 'get_user'
    )
    app = web.application(urls, globals())
    print "Starting web server"
    app.run()

  def stop(self):
    print "Stopping web server"
    os._exit(0)    
#    self.process.terminate()
#    self.process = None

#class list_users:
#    def GET(self):
#        output = 'users:[';
#        for child in root:
#                print 'child', child.tag, child.attrib
#                output += str(child.attrib) + ','
#        output += ']';
#        return output

class show_card_id:
  def GET(self):
    return json.dumps({
      'cardid': currentcard
    })

class show_carduser:
  def GET(self):
    return json.dumps({
      'cardid': currentcard,
      'user': cardusers.get(currentcard, 'No User')
    })


def process_tag_data(tag):
    inloop=True
    tag_id = tag.identifier.encode('hex').upper()
 #   print 'Tag ID is', tag_id
    global currenttag
    currenttag=tag_id
#    print "Cur:",currenttag
#    time.sleep(1000)


#set up card reader
clf = nfc.ContactlessFrontend('usb')
print 'NFC reader', clf, 'opened'

#print 'Stating web server'
webthread=MyWebserver()
webthread.start()

print 'entering loop'

while True:
#  clf.connect(rdwr=rdwr_options)      # Blocking, don't use
#  print "Curr:",currenttag," Prev:",prevtag

  currenttag=0
  # Try and read, give up after 1 second.
  after1s = lambda: time.time() - started > 1
  started = time.time(); clf.connect(rdwr={'on-connect': process_tag_data}, terminate=after1s)

  if currenttag == '041FBDE21A2681':
    print 'BLACKTAG! Existing..'
    webthread.stop()
    exit()

#  print "Current:",currenttag,"  Prev:",prevtag
  if prevtag==0 and currenttag==0:
    print "Waiting for next card."
  elif currenttag==prevtag:
    print "Card read, please remove card."
    # keep this if we want to keep info up while card is held on reader
    last_tag_read_time = time.time()
  else:
    prevtag=currenttag
    if currenttag != 0:
      # global declaraion not needed since we're outside a class/function
      currentcard = currenttag
      last_tag_read_time = time.time()
      print 'Tag ID:',currenttag,'User',cardusers.get(currenttag, 'No User')

  # clear tag data after a timeout
  if last_tag_read_time + tag_data_timeout < time.time():
    last_tag_read_time = time.time()
    currentcard = None
    print "Card timeout."

  if currenttag != 0:
    time.sleep(0.5)
#  print "Looping"


