import logging
import subprocess
import time

import cv2
import numpy as np

from flandre.BusClient import BusClient
from flandre.config import C
from flandre.nodes.Node import Node
from flandre.utils.Msg import Msg, RfMatMsg
from flandre.utils.RfMat import RfMat

logger = logging.getLogger(__name__)


class ImageFFMPEG(Node):
    topics = [RfMatMsg]

    def __init__(self, level=logging.INFO):
        super().__init__(level=level)
        self.buffer = np.zeros((C.video_height, C.video_width, 3), dtype=np.uint8) + 128
        self.buffer = self.buffer.tobytes()

    def loop(self):
        self.c = BusClient(RfMatMsg, pub=False, conflare=True, poller=True)
        p = subprocess.Popen(['ffmpeg',
                              '-f', 'rawvideo',
                              '-pixel_format', 'rgb24',
                              '-video_size', f'{C.video_width}x{C.video_height}',
                              '-framerate', '24',
                              '-hwaccel', 'nvdec',
                              '-i', '-',
                              '-vcodec', 'h264_nvenc',
                              '-preset', 'fast',
                              '-gpu', '1',

                              # '-profile:v', 'high',
                              '-zerolatency', '1',
                              # '-tune', 'ull',
                              # '-level', '42',

                              '-pix_fmt', 'yuv420p',
                              # '-vcodec', 'libx264',
                              # '-b:v', '40M',
                              '-f', 'flv',
                              # 'rtmp://q1hyb.as/live/bscan',
                              'rtmp://11.2.1.21/live/bscan',
                              # '-f', 'mpegts',
                              # 'srt://localhost:10080?streamid=#!::r=live/livestream,m=publish'
                              ],
                             stdin=subprocess.PIPE,
                             )
        lasttime = time.time()
        while True:
            # socks = dict(self.c.poller.poll(1 / 30))
            events = self.c.poller.poll(1000 / 24)
            if events:
                msg: RfMatMsg = Msg.decode_msg(events[0][0].recv())
                rfmat: RfMat = msg.rfmat
                self.buffer = (rfmat
                               .grey()
                               .resize((C.video_width, C.video_height))
                               .watermark()
                               .call(cv2.cvtColor, cv2.COLOR_GRAY2RGB)
                               .__bytes__()
                               )
            p.stdin.write(self.buffer)
            # time.sleep(1 / 60)
            currenttime = time.time()
            logger.debug(f'{currenttime - lasttime}')
            lasttime = currenttime


if __name__ == '__main__':
    ImageFFMPEG()()
