#!/usr/bin/env python

import cv2
import logging
import time
import zbarlight

from PIL import Image


logger = logging.getLogger(__name__)


class QRCodeReader:
    def __init__(self):
        super().__init__()
        self.open_cam()

    def open_cam(self):
        self.video_capture = cv2.VideoCapture(0)

    def read_cam(self):
        rval, frame = self.video_capture.read()
        if frame is None or not frame.any():
            return None
        pil_img = Image.fromarray(frame)
        return zbarlight.scan_codes('qrcode', pil_img)

    def close_cam(self):
        self.video_capture.release()

    def run(self):
        while True:
            self.read()
            time.sleep(0.2)

    def read(self):
        code = self.read_cam()
        if code:
            return code[0].decode('utf8')


if __name__ == '__main__':
    qrcode_reader = QRCodeReader()
    try:
        qrcode_reader.run()
    finally:
        qrcode_reader.close_cam()
