from edge_engine.common.logsetup import logger
from edge_engine.streamio.videostream import NVGstreamer


class SimpleVideoStream:
    def __init__(self, stream_config, name="SimpleVideoStream"):
        self.stream_config = stream_config
        self.build_pipeline()
        (self.grabbed, self.frame) = self.stream.read()
        self.name = name

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

    def start(self):
        logger.info("Starting video stream ")
        if self.stream.isOpened():
            self.grabbed, self.frame = self.stream.read()
            if self.grabbed is False:
                logger.error("Empty Frame !!!! ")
                logger.error("Error opening Capture !!!! ")
                self.build_pipeline()
            return self
        else:
            logger.error("Error opening Capture !!!! ")
            self.build_pipeline()

    def is_opened(self):
        return self.stream.isOpened()

    def read(self):
        # return the frame most recently read
        if self.stream.isOpened():
            self.grabbed, self.frame = self.stream.read()
            if self.grabbed is False:
                logger.error("Empty Frame !!!! ")
                raise ValueError("Empty Frame !!!! ")
            return self.frame
        else:
            logger.error("Error opening Capture !!!! ")
            raise ValueError("Error opening Capture !!!! ")

    def stop(self):
        if self.stream.isOpened():
            self.stream.release()
