from threading import Thread


def is_alive(subprocess):
    return True if (subprocess and subprocess.poll() is None) else False


class Streamer:
    PROTOCOL = "rtsp"
    REST_PATH = "stream"

    def __init__(self):
        self.run = False
        self.thread = None
        self.name = None

    def stream_path(self):
        return f"{type(self).REST_PATH}/{self.name}"

    def stream_address(self, host, port=8554):
        return f"{type(self).PROTOCOL}://{host}:{port}/{self.stream_path()}"

    def is_streaming(self):
        return True if (self.thread and self.thread.is_alive()) else False

    def start_stream(self):
        if self.is_streaming():
            raise RuntimeError("Stream thread is already running")

        self.run = True
        self.thread = Thread(target=self._stream_thread, daemon=True, args=())
        self.thread.start()

    def end_stream(self):
        if self.thread is None:
            raise RuntimeError("No stream thread to terminate")

        self.run = False
        self.thread.join()
        self.thread = None
