#! /usr/bin/env python3

"""
# Install issues?
https://stackoverflow.com/a/27481870

https://stackoverflow.com/a/66024755
sudo apt purge youtube-dl
sudo pip3 install youtube-dl

https://stackoverflow.com/a/75504772
python3 -m pip install --force-reinstall https://github.com/yt-dlp/yt-dlp/archive/master.tar.gz
"""

#import youtube_dl
import yt_dlp as youtube_dl
from streamer import Streamer, is_alive
import subprocess
import time
import sys


class Tuuube(Streamer):
    PORT = 8554

    def __init__(self, id):
        self.id = id
        self.playback = None
        super().__init__()

    def is_playing(self):
        return is_alive(self.playback)

    def _stream_path(self):
        return f":{Tuuube.PORT}/tuuube/{self.id}"

    def _stream_thread(self):
        ydl_opts = {
            'format': 'bestaudio/best',
            'outtmpl': f'/tmp/{self.id}.%(ext)s',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }

        try:
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([f'https://www.youtube.com/watch?v={self.id}'])
        except Exception as e:
            print(f'File sourcing failed, aborting stream. {e}', file=sys.stderr)
            self.run = False
            return

        self.playback = subprocess.Popen(
            [
                '/usr/bin/ffmpeg', '-re', '-stream_loop', '-1', '-i',
                f"/tmp/{self.id}.mp3", '-c', 'copy',
                '-f', 'rtsp', f"rtsp://localhost{self._stream_path()}"
            ],
            stdin=subprocess.PIPE,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )

        while self.run:
            if not self.is_playing():
                print('Playback failed, aborting stream.', file=sys.stderr)
                break
            time.sleep(0.1)

        self.run = False

        self.playback.kill()
        self.playback.wait()
        self.playback = None



if __name__ == '__main__':
    #tube = Tuuube('dQw4w9WgXcQ')
    tube = Tuuube('BaW_jenozKc')

    tube.start_stream()

    while True:
        print(tube.is_streaming())
        time.sleep(1)