import subprocess
import threading

from PyQt6 import QtCore

from flandre.nodes.Node import Node


class FFmpegReceiver(QtCore.QObject):
    zmq_event = QtCore.pyqtSignal('QByteArray')

    def __init__(self, url: str, parent=None):
        super().__init__(parent)
        self.url = url

    def start(self):
        threading.Thread(target=self._execute, daemon=True).start()

    def _execute(self):
        p = subprocess.Popen([
            'ffmpeg',
            '-loglevel', 'quiet',
            '-flags', 'low_delay',
            '-fflags', 'nobuffer',
            '-i', self.url,
            '-pix_fmt', 'rgb24',
            '-f', 'rawvideo',
            '-'
        ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        while True:
            self.zmq_event.emit(p.stdout.read(1920 * 1080 * 3))
