import requests
import zbarlight
import os
import sys
import PIL

print 'Taking picture..'
try:
    f = 1
    qr_count = len(os.listdir('qr_codes'))
    os.system('sudo fswebcam -d /dev/video'+sys.argv[1]+' -q qr_codes/qr_'+str(qr_count)+'.jpg')
    print 'Picture taken..'
except:
    f = 0
    print 'Picture couldn\'t be taken..'

print

if(f):
    print 'Scanning image..'
    f = open('qr_codes/qr_'+str(qr_count)+'.jpg','rb')
    qr = PIL.Image.open(f);
    qr.load()

    codes = zbarlight.scan_codes('qrcode',qr)
    if(codes==None):
        os.remove('qr_codes/qr_'+str(qr_count)+'.jpg')
        print 'No QR code found'
    else:
        print ' ' 
        requestString = 'http://192.168.1.30:8000/tickets/validate/{}'.format(codes[0])
        print 'requestUrl', requestString
        print ' '
        print 'ticket id:', codes[0]
        r = requests.get(requestString)
        
        print 'valid:',r.json()['valid']