# 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 io
import sys
import time
import logging
try:
    import picamera
except ImportError:
    logging.error("Can't import picamera module. Please install it with apt-get install python-picamera")
    picamera = None

import config
from base_cam import BaseCamera, BaseCaptureWrapper


class PiCameraCapture(BaseCaptureWrapper):

    QUALITY = 10 # not jpeg quality, but internal picamera parameter
    IMAGE_EXT = "jpeg"

    def __init__(self, parent, cloud_camera_number):
        super().__init__(parent, cloud_camera_number)
        if picamera:
            try:
                capture = picamera.PiCamera()
                capture.resolution = (self.X_RESOLUTION, self.Y_RESOLUTION)
                self.logger.info("Got connection to PiCamera")
                self.capture = capture
            except:
                self.logger.exception("Can't init PiCamera. Camera seems to be not connected or not enabled in RPi config.")
            else:
                self.fails = 0
                self.cloud_camera_state = 1
        else:
            self.logger.warning('Picamera back')

    def get_frame(self):
        stream = io.BytesIO()
        self.capture(stream, format=self.IMAGE_EXT, quality=self.QUALITY)
        return stream.getvalue()


class RPiCamera(BaseCamera):

    CAPTURE_CLASS = PiCameraCapture


if __name__ == "__main__":
    RPiCamera().run()
