# Copyright 3D Control Systems, Inc. All Rights Reserved 2017-2019.
# Built in San Francisco.

# This software is distributed under a commercial license for personal,
# educational, corporate or any other use.
# The software as a whole or any parts of it is prohibited for distribution or
# use without obtaining a license from 3D Control Systems, Inc.

# All software licenses are subject to the 3DPrinterOS terms of use
# (available at https://www.3dprinteros.com/terms-and-conditions/),
# and privacy policy (available at https://www.3dprinteros.com/privacy-policy/)

import dual_cam
import platforms


class Camera(dual_cam.Camera):

    def search_cameras(self):
        self.camera_names = []
        dual_cam.Camera.search_cameras(self)

    def init_capture(self, capture_name, backend=None):
        if super().init_capture(capture_name, backend):
            capture = self.captures.pop()
            capture.release()
            self.camera_names.append(capture_name)
            self.captures.append(capture)

    def make_shot(self, number, capture):
        try:
            if platforms.PLATFORM in ("rpi", "linux"):
                capture = self.cv2.VideoCapture(self.camera_names[number], self.cv2.CAP_V4L2)
            else:
                capture = self.cv2.VideoCapture(self.camera_names[number])
            print('Capture', self.camera_names[number], capture)
        except Exception as e:
            self.logger.warning("Error while opening video capture: " + str(e))
            self.fails[number] += 1
        else:
            if capture.isOpened():
                frame = dual_cam.Camera.make_shot(self, number, capture)
                capture.release()
                return frame
            else:
                capture.release()
                return []


if __name__ == "__main__":
    Camera()
