# 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

import config
import dual_cam

class Camera(dual_cam.Camera):

    INACTIVE_LOOP_TIME = 3
    QUALITY = 10 # not jpeg quality, but internal picamera parameter
    X_RESOLUTION = 640
    Y_RESOLUTION = 640
    QUALITY = 10
    IMAGE_EXT = "jpeg"

    def __init__(self, autostart=True):
        self.stop_flag = False
        self.pre_init(autostart)
        self.init_settings()
        self.init_user_token()
        self.init_parameters()
        try:
            import picamera
        except ImportError:
            logging.error("Can't import picamera module. Please install it with apt-get install python-picamera")
        else:
            try:
                self.capture = picamera.PiCamera()
                self.capture.resolution = (self.X_RESOLUTION, self.Y_RESOLUTION)
                self.logger.info("Got connection to PiCamera")
            except:
                self.logger.exception("Can't init PiCamera. Camera seems to be not connected or not enabled in RPi config.")
            else:
                self.resized.append(True)
                self.fails.append(0)
                self.cloud_camera_state[0] = 1
                if autostart:
                    self.main_loop()

    def start(self):
        self.main_loop()

    def main_loop(self):
        time.sleep(self.MIN_LOOP_TIME)
        while not self.stop_flag:
            frame_start_time = time.monotonic()
            if self.cloud_camera_state[self.active_camera_number]:
                stream = io.BytesIO()
                self.capture.capture(stream, format=self.IMAGE_EXT, quality=self.QUALITY)
                frame = stream.getvalue()
                self.send_frame(frame)
                min_loop_time = self.MIN_LOOP_TIME
            else:
                self.send_frame(self.SAME_IMAGE)
                min_loop_time = self.INACTIVE_LOOP_TIME
            while time.monotonic() < frame_start_time + 0.001 + min_loop_time:
                time.sleep(0.01)
        self.http_client.close()
        self.capture.close()
        self.capture = None
        sys.exit(0)


if __name__ == "__main__":
    Camera()
