import time

import cv2
import numpy as np

import config
import cv_cam, base_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.create_capture()
        super().__init__(parent, cap_id)

    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, str(counter+1), (240,300), self.FONT, 3, (255,255,255), 2, cv2.LINE_AA)
            self.images.append(image)
            counter += 1
        self.active = True

    def release_capture(self):
        self.active = False
        self.images = []

    def frame_loop(self):
        while not self.stop_flag:
            if self.counter == self.IMAGES_COUNT:
                self.counter = 0
            try:
                self.frame = self.images[self.counter]
            except IndexError:
                print(self.counter, len(self.images))
            self.counter += 1
            time.sleep(0.5)


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
