import time

import cv2
import numpy as np

import config
import base_cam
import cv_cam


class VirtualCaptureWrapper(cv_cam.OpenCVFFMPEGCaptureWrapper):

    ID = 'VIRTUAL'
    TITLE = '3DPrinterOS'

    IMAGES_COUNT = 24
    FONT = cv2.FONT_HERSHEY_DUPLEX
    W = 640
    H = 480

    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((self.H, self.W, 3), np.uint8)
            w_center = self.W // 2
            (title_w, _), _ = cv2.getTextSize(self.TITLE, self.FONT, 1, 1)
            cv2.putText(image, self.TITLE, (w_center - title_w // 2, self.H // 2 - 40), self.FONT, 1, (255, 255, 255), 1, cv2.LINE_AA)
            (cap_w, _), _ = cv2.getTextSize(self.cap_id, self.FONT, 1, 1)
            cv2.putText(image, self.cap_id, (w_center - cap_w // 2, self.H // 2 + 10), self.FONT, 1, (255, 255, 255), 1, cv2.LINE_AA)
            counter_str = str(counter + 1)
            (counter_w, _), _ = cv2.getTextSize(counter_str, self.FONT, 3, 2)
            cv2.putText(image, counter_str, (w_center - counter_w // 2, self.H // 2 + 100), 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
