#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This application is released under the GNU General Public License 
# v3 (or, at your option, any later version). You can find the full 
# text of the license under http://www.gnu.org/licenses/gpl.txt
# By using, editing and/or distributing this software you agree to 
# the terms and conditions of this license.
#_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

import dbus, sys

DBUS_NAME = 'org.mpris.soundz'

(ADD, SET, NEXT, PREV, PLAY, STOP, VOLUME) = range(7)
(CMD_ARGS, CMD_HELP, CMD_NAME) = range(3)

commands = {
    'add':      ( 'dir/file...',    'append to playlist',   ADD     ),
    'set':      ( 'dir/file...',    'set new playlist',     SET     ),
    'next':     ( '',               'go to next track',     NEXT    ),
    'prev':     ( '',               'go to previous track', PREV    ),
    'play':     ( '',               'play/pause playback',  PLAY    ),
    'stop':     ( '',               'stop playback',        STOP    ),
    'volume':   ( 'value (0/10)',   'set volume',           VOLUME  ),
           }

cmdLineOk = False

if len(sys.argv) > 1:
    cmdName = sys.argv[1]

    if cmdName in commands:
        cmdLineOk = True
    elif len(sys.argv) == 2 and commands[cmdName][CMD_ARGS] != '':
        print '%s needs some arguments'       % cmdName
    elif len(sys.argv) > 2 and commands[cmdName][CMD_ARGS] == '':
        print '%s does not take any argument' % cmdName

if not cmdLineOk:
    print 'Usage: soundz-cli [command] [dir/file/url]\n'
    print 'Commands:'
    for cmd, data in sorted(commands.iteritems()):
        print '%s %s %s' % (cmd.ljust(7), data[CMD_ARGS].ljust(14), data[CMD_HELP])
    sys.exit()

session = dbus.SessionBus()
activeServices = session.get_object(
    'org.freedesktop.DBus', '/org/freedesktop/DBus').ListNames()
if not DBUS_NAME in activeServices:
    sys.exit()
player = dbus.Interface(session.get_object(DBUS_NAME, '/Player'),
    'org.freedesktop.MediaPlayer')
tracklist = dbus.Interface(session.get_object(DBUS_NAME, '/TrackList'),
    'org.freedesktop.MediaPlayer')

cmd = commands[cmdName][CMD_NAME]
if   cmd == SET:    tracklist.SetTracks(sys.argv[2:], True)
elif cmd == ADD:    tracklist.AddTracks(sys.argv[2:], False)
elif cmd == NEXT:   player.Next()
elif cmd == PREV:   player.Prev()
elif cmd == PLAY:   player.Pause()
elif cmd == STOP:   player.Stop()
elif cmd == VOLUME: player.VolumeSet(int(sys.argv[2])*10)
