#! /usr/bin/env python3

"""
We aren't using either the apt or the pip repositories for the youtube_dl
as there is a known bug affecting those two versions. The youtube API has changed
since their release, causing downloads to fail.
Make sure you use the ./setup.sh script to obtain the latest github release of
yt_dlp, as this version carries the latest fixes.
"""
#import youtube_dl
import yt_dlp as youtube_dl
from streamer import Streamer, is_alive
import subprocess
import time
import sys
import os


class Tuuube(Streamer):
    REST_PATH = 'tuuube'

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

    def source_path(self):
        return f"/tmp/{self.name}.mp3"

    def _stream_thread(self):
        if not os.path.exists(self.source_path()) or not os.path.isfile(self.source_path()):
            ydl_opts = {
                'format': 'bestaudio/best',
                'outtmpl': f'/tmp/{self.name}.%(ext)s',   # yt_dlp will append %(ext) if not specified,
                'postprocessors': [{                    # resulting in `/tmp/file.mp3.mp3` :/
                    '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.name}'])
            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', self.source_path(),
                '-c', 'copy',
                '-f', 'rtsp',
                self.stream_address('localhost')
            ],
            stdin=subprocess.PIPE,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )

        while self.run:
            if not is_alive(self.playback):
                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('BaW_jenozKc')
    tube.start_stream()

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