#!/usr/bin/python
from sys import argv
import zbar
import threading
import sys
import re


#Initailizes a codeReader object
#Params:
# sourceDevice: The file mapping for the source device (/dev/video0 if a single webcam is attached)
def main(sourceDevice='/dev/video0'):
    #initailize a thread to host the card reader logic

    # A zbar Processor is a stream monitor (in this case, for the webcam's video stream)
    monitor = zbar.Processor()
    monitor.parse_config('enable')
    monitor.init(sourceDevice)

    # disable the preview window
    monitor.visible = True

    regex = re.compile("^BOKS_[0-9]{5}$")

    #The zbar Processor will call this event handler when input is available
    # The handler follows the (otherwise undocumented) example usage from the source's repo
    # We'll retain the unused hostProcessor and closure parameters for signature matching
    def receiveCode(monitor, codeStream, closure):
        for symbol in monitor.results:
            # do something useful with results
            if regex.match(symbol.data):
                print symbol.data
                sys.stdout.flush()

    # Connect our event handler for input
    monitor.set_data_handler(receiveCode)

    #set up input and input control members
    latestRead = ""
    latestReadType = ""

    #scan continuously, pausing if the input is being held for reading
    monitor.active = True

    while True:
        monitor.process_one()
        for symbol in monitor.results:
            # do something useful with results
            print symbol.type, ', ', '"%s"' % symbol.data
            sys.stdout.flush()


main()
