#!/usr/bin/env python
import json, os, re, subprocess, sys, xbmc

def main():
    target_name = "alsa_output.pci-0000_00_1b.0.analog-stereo"
    target_vol = 100
    if sys.argv[1] == "2":
        target_name = "raop_output.XC-HM71.local"
        target_vol = 25
    if sys.argv[1] == "3":
        target_name = "alsa_output.pci-0000_05_00.1.hdmi-stereo"
        target_vol = 100
    
    sinks = get_sinks()
    target_sink = None
    for sink in sinks:
        if target_name == sink.name:
            target_sink = sink

    if target_sink != None:
        for stream in get_streams():
            move_stream(stream, target_sink)    
        xbmc.executebuiltin( "XBMC.SetVolume(%d)" % ( target_vol, ) )

def get_sinks():
    output = subprocess.check_output(["pactl", "list", "short", "sinks"])
    result = []

    for line in output.split("\n"):
        if re.match(r'\w', line):
            fields = re.split(r'\s+', line)
            result.append(PulseAudioSink(*fields))

    return result

def get_streams():
    output = subprocess.check_output(["pactl", "list", "short", "sink-inputs"])
    result = []
    
    for line in output.split("\n"):
        if re.match(r'\w', line):
            fields = re.split(r'\s+', line)
            result.append(PulseAudioStream(*fields))

    return result

def move_stream(stream, sink):
    return_code = subprocess.call(["pactl", "move-sink-input", str(stream.id),  str(sink.id)])
    if return_code != 0:
        raise Exception("Unable to transfer the stream: {}".format(return_code))

class PulseAudioSink:
    id = None
    name = None
    driver = None
    audio_format = None
    audio_channels = None
    audio_sample_rate = None
    state = None

    def __init__(self, id = None, name = None,
            driver = None, audio_format = None,
            audio_channels = None, audio_sample_rate = None,
            state = None):
        self.id = int(id)
        self.name = name
        self.driver = driver
        self.audio_format = audio_format
        self.audio_channels = re.match(r'(^\d+)ch', audio_channels).group(1)
        self.audio_sample_rate = re.match(r'(\d+)Hz', audio_sample_rate).group(1)
        self.state = state

class PulseAudioStream:
    id = None
    sink_id = None
    client_id = None
    driver = None
    audio_format = None
    audio_channels = None
    audio_sample_rate = None

    def __init__(self, id = None, sink_id = None,
            client_id = None, driver = None, audio_format = None,
            audio_channels = None, audio_sample_rate = None):
        self.id = id
        self.sink_id = sink_id
        self.client_id = client_id
        self.driver = driver
        self.audio_format = audio_format
        self.audio_channels = audio_channels
        self.audio_sample_rate = audio_sample_rate
    

if __name__ == "__main__":
    main()
