# import the necessary packages
from threading import Thread
import time
from edge_engine.streamio.videostream import NVGstreamer
from edge_engine.common.logsetup import logger


class ThreadedVideoStream:
    def __init__(self, stream_config, name="ThreadedVideoStream"):
        # initialize the video camera stream and read the first frame
        # from the stream
        self.stream_config = stream_config
        self.build_pipeline()
        # self.stream = stream
        (self.grabbed, self.frame) = self.stream.read()
        # initialize the thread name
        self.name = name

        # initialize the variable used to indicate if the thread should
        # be stopped
        self.stopped = False

    def build_pipeline(self):
        self.gstreamer = NVGstreamer(self.stream_config)
        self.gstreamer.build_pipeline()
        self.stream = self.gstreamer.get_stream()

    def start(self):
        # start the thread to read frames from the video stream
        t = Thread(target=self.update, name=self.name, args=())
        t.daemon = True
        t.start()
        return self

    def update(self):
        # keep looping infinitely until the thread is stopped
        while True:
            # if the thread indicator variable is set, stop the thread
            if self.stopped:
                return

            # otherwise, read the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()
            if self.grabbed is False or self.frame is None:
                logger.error("Empty Frame !!!! ")
                logger.error("Error opening Capture !!!! ")
                self.build_pipeline()

    def read(self):
        # return the frame most recently read
        return self.frame

    def stop(self):
        # indicate that the thread should be stopped
        self.stopped = True
        time.sleep(0.2)
        self.stream.release()
