"""Capture ONE photo from the kiosk's camera with OpenCV (CAPTURE_MODE=opencv)."""
import sys
import threading

import cv2
from django.conf import settings

_lock = threading.Lock()  # one camera, one photo at a time


class CameraError(Exception):
    """The camera could not be opened or gave no picture."""


def _source():
    value = str(settings.CAMERA_SOURCE).strip()
    return int(value) if value.isdigit() else value  # "0" -> camera 0; anything else = a video file (testing)


def capture_frame():
    """Open the camera, let it adjust, take one picture, close the camera. Returns a BGR image."""
    with _lock:
        source = _source()
        is_camera = isinstance(source, int)
        backend = cv2.CAP_DSHOW if (is_camera and sys.platform == "win32") else cv2.CAP_ANY  # DSHOW opens faster on Windows
        cap = cv2.VideoCapture(source, backend)
        try:
            if not cap.isOpened():
                raise CameraError("Could not open the camera. Check that it is plugged in, not used by another "
                                  "program, and that CAMERA_SOURCE is the right number.")
            if is_camera:
                cap.set(cv2.CAP_PROP_FRAME_WIDTH, settings.CAMERA_WIDTH)
                cap.set(cv2.CAP_PROP_FRAME_HEIGHT, settings.CAMERA_HEIGHT)
            frame = None
            for _ in range(max(1, settings.CAMERA_WARMUP_FRAMES)):  # the first frames are often dark
                ok, image = cap.read()
                if ok:
                    frame = image
            if frame is None:
                raise CameraError("The camera did not deliver a picture.")
            return frame
        finally:
            cap.release()  # camera light off right away
