#!/usr/bin/env python                                                                                                                                      
# -*- coding: utf-8 -*-                                                                                                                                    

import sys
from palib import PulseObj, \
                  PulseSink, \
                  PulseSinkInfo, \
                  PulseSinkInputInfo, \
                  PulseVolume


# fills free slots in balance with default values.
# channels: front left, front right, rear left, rear right, front center, subwoofer
def balanceSetup(balance):
    levels = [int(channel) for channel in balance]
    freeSlots = 6 - len(levels)
    if freeSlots == 5:
        # only one value: set all channels to the same value.
        levels *= 6
    else:
        # less than 6 values: set remaining channels to 100.
        levels += [100] * freeSlots
    return levels


# changes a sink's volume accordingly to a given delta.
def changeVolume(sink, delta):
    volume = sink.volume
    for channel in range(0, volume.channels):
        volume.values[channel] = int(volume.values[channel] + delta)
    return volume


# sets a sink's volume to a given balance.  
def setVolume(sink, balance):
    volume = sink.volume
    for channel in range(0, volume.channels):
        volume.values[channel] = int(balance[channel])
    return volume


# initialize the main PulseObj. 
pulse = PulseObj("pactl.py", None, True)


if sys.argv[1] == 'sink':
    sinks = pulse.pulse_sink_list()
    sink = sinks[int(sys.argv[2])]    

    if sys.argv[3] == 'toggle':
        if sink.mute == 0: 
            pulse.pulse_mute_sink(sink.index)
        else:
            pulse.pulse_unmute_sink(sink.index)

    else:
        if sys.argv[3] == 'incvolume':
            newVolume = changeVolume(sink, int(sys.argv[4]))

        elif sys.argv[3] == 'setvolume':
            newVolume = setVolume(sink, balanceSetup(sys.argv[4:10]))
        
        else:
          print "Unknown command '%s'." % sys.argv[3]
          quit()
          
        print "Setting volume levels to: %s" % newVolume.values
        pulse.pulse_set_sink_volume(sink.index, newVolume)
        for stream in pulse.pulse_sink_input_list():
            pulse.pulse_set_sink_input_volume(stream.index, newVolume)
  