import time

import cv2
import numpy as np

import config
import base_cam
import cv_cam


class VirtualCaptureWrapper(cv_cam.OpenCVFFMPEGCaptureWrapper):

    ID = 'VIRTUAL'

    IMAGES_COUNT = 24
    FONT = cv2.FONT_HERSHEY_COMPLEX

    def __init__(self, parent, cap_id):
        self.counter = 0
        self.images = []
        self.cap_id = cap_id
        self.create_capture()
        super().__init__(parent, cap_id)
        self.need_software_resize = False

    def create_capture(self):
        self.images = []
        counter = 0
        while counter < self.IMAGES_COUNT:
            image = np.zeros((480,640,3), np.uint8)
            cv2.putText(image, '3DPrinterOS', (200,160), self.FONT, 1, (255,255,255), 1, cv2.LINE_AA)
            cv2.putText(image, self.cap_id, (235,200), self.FONT, 1, (255,255,255), 1, cv2.LINE_AA)
            if counter < 9:
                x = 270
            else:
                x = 245
            cv2.putText(image, str(counter+1), (x,300), self.FONT, 3, (255,255,255), 2, cv2.LINE_AA)
            self.images.append(image)
            counter += 1
        self.active = True

    def frame_loop(self):
        while not self.stop_flag:
            if self.counter == self.IMAGES_COUNT:
                self.counter = 0
            with self.frame_lock:
                try:
                    self.frame = self.images[self.counter]
                except IndexError:
                    pass
            self.counter += 1
            time.sleep(base_cam.BaseCamera.MIN_SEC_PER_FRAME-0.01)
        self.deactivation_cleanup()


class VirtualDetector(base_cam.BaseCamDetector):

    CAPTURE_WRAPPER_CLASS = VirtualCaptureWrapper

    def get_capture_ids(self):
        captures = []
        for c in range(int(config.get_settings()['camera'].get('virtual', 0))):
            captures.append('Virtual' + str(c+1))
        return captures
