import traceback
import random
import threading
import os
import logging
import subprocess
import pydbus
from gi.repository import GLib
from collections import deque
import signal
import time
import sys

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logger = logging.getLogger('yt-live')

class YTLiveCTM(threading.Thread):
    """
    <node>
        <interface name='party.segfault.muziekbeen.CustomTrackManager'>
            <method name='preTrack'>
                <arg type='(sssd)' name='trackInfo' direction='in'/>
                <arg type='s' name='arg' direction='in'/>
            </method>
            <method name='postTrack'>
                <arg type='s' name='arg' direction='in'/>
            </method>
        </interface>
    </node>
    """
    def run(self):
        self.loop = GLib.MainLoop()
        self.bus = pydbus.SystemBus()
        self.process = None

        self.object_path = "/party/segfault/muziekbeen/YTLive"
        self.bus.publish("party.segfault.muziekbeen.YTLive", self)

        self.loop.run()

    def preTrack(self, trackInfo, url):
        print(f"preTrack {trackInfo} {url}")
        try:
            os.unlink('sound.pipe')
        except FileNotFoundError:
            pass
        os.mkfifo('sound.pipe')
        self.process = subprocess.Popen(
            ["/home/muziekbeen/muziekbeen/ytlivepipe.sh", url], stdout=subprocess.PIPE,
            text=True)

    def postTrack(self, arg):
        print("postTrack called")
        if self.process is not None and self.process.poll() is None:
            self.process.kill()

class YTLive:
    def __init__(self):
        self.loop = GLib.MainLoop()
        self.bus = pydbus.SystemBus()

        self.object_path = "/party/segfault/muziekbeen/YTLive"

        self.ctm = YTLiveCTM(daemon=True)
        self.ctm.start()

        logger.info("Waiting for Muziekbeen on the bus...")
        while True:
            try:
                time.sleep(0.1)
                self.mb = self.bus.get('party.segfault.muziekbeen', '/party/segfault/muziekbeen')
            except GLib.Error:
                continue
            except KeyboardInterrupt:
                sys.exit()
            else:
                break
        logger.info("Got Muziekbeen bus proxy.")

    def run(self):
        logger.info("Connecting to signals.")
        self.mb.command.connect(self.command)

        logger.info("Running event loop.")
        try:
            self.loop.run()
        except:
            traceback.print_exc()

    def command(self, user, command):
        logger.info(f"Non-core command run by {user}: {command}")
        cmd, *args = command.split(' ', 1)
        args = "" if not args else args[0]
        args = args.replace('[URL]', '').replace('[/URL]', '')
        if cmd == ".ytlive":
            self.start_live(args)

    def start_live(self, args):
        if not args.startswith('https://'):
            return self.mb.sendMessage("that doesn't look like a url...")
            
        self.mb.playTrackEx(self.object_path, args, 'some', 'youtube', 'livestream', "./sound.pipe", 360000)


ytlive = YTLive()
ytlive.run()

