#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2005 İsmail Dönmez (Resistence is futile, turn on unicode!)
# Licensed under GPLv2 or later at your option
#
# One media command to rule them all, inspired from Kopete's now listening plugin

global pyxmmsInstalled;

import os
import sys

port = sys.argv[1]
server = sys.argv[2]
target = sys.argv[3]


try:
    import xmms.common
    pyxmmsInstalled = True;
except ImportError:
    pyxmmsInstalled = False;

try:
    from subprocess import *
except ImportError:

    if (sys.hexversion >> 16) < 0x0204:
        err="The media script requires python 2.4 (or the subprocess module from same)"
    else:
        err="The media script could not import subprocess module"
    os.popen('dcop %s default error "%s"'%(port,err))
    raise

global port;
global server;
global target;

# checks for running dcop-aware media players
def check_running(application):
    running = Popen(["dcop", application+'*'], stdout=PIPE).communicate()[0]
    if type(running) is list:
        return running[0].strip()
    return running.strip()

def reencodeString(input):
    if input:
        try:
            input = input.decode('utf-8')
        except UnicodeError:
            try:
                input = input.decode('latin-1')
            except UnicodeError:
                input = input.decode('ascii', 'replace')
        except NameError:
                pass
    return input.encode('utf-8')

def pretty_print(title, artist='', album=''):
    if title:
        title = reencodeString(title)
    if artist:
        artist = reencodeString(artist)
    if album:
        album = reencodeString(album)

    if (artist and album) and (artist != album):
        return "/me is listening to \"%s\" by %s on %s"%(title,artist,album)
    elif artist:
        return "/me is listening to \"%s\" by %s"%(title,artist)
    elif album:
        return "/me is listening to \"%s\" on %s"%(title,album)
    else:
        return "/me is listening to \"%s\""%(title)

if __name__ == "__main__":
    bad_apps = None
    error = None

    # define variables to avoid errors
    title = '';
    artist = '';
    album = '';

    # only try to acquire title if xmms support in python is present
    if pyxmmsInstalled:
        # check if xmms is running
        xmmsRunning = xmms.control.is_running()

        if xmmsRunning:
            # check if xmms is playing something
            if xmms.control.is_playing():
                # get the position in the playlist for current playing track
                pos = xmms.control.get_playlist_pos();
                # get the title of the currently playing track
                title = xmms.control.get_playlist_title(pos)

            # if there really is something playing
            if title:
                # format title and tell konversation about it
                string = pretty_print(title)+' [xmms]'
                Popen(['dcop', port, 'default', 'say', server, target, string]).communicate()
                sys.exit(0)
            # xmms running but nothing's playing
            else:
                # remember to tell the user later in the script
                error = True
                bad_apps = ['xmms']

    amarok = check_running('amarok')
    if amarok:
        title = os.popen('dcop '+amarok+' player title').readline().rstrip('\n')
        artist = os.popen('dcop '+amarok+' player artist').readline().rstrip('\n')
        album = os.popen('dcop '+amarok+' player album').readline().rstrip('\n')

        if not title:
            title = os.popen('dcop '+amarok+' player nowPlaying').readline().rstrip('\n')

        if title:
            string = pretty_print(title,artist,album)+' [Amarok]'
            Popen(['dcop', port, 'default', 'say', server, target, string]).communicate()
            sys.exit(0)
        else:
            error = True
            bad_apps = ['Amarok']

    juk = check_running('juk')
    if juk:
        title = os.popen('dcop '+juk+' Player trackProperty Title').readline().rstrip('\n')
        artist = os.popen('dcop '+juk+' Player trackProperty Artist').readline().rstrip('\n')
        album = os.popen('dcop '+juk+' Player trackProperty Album').readline().rstrip('\n')

        if title:
            string = pretty_print(title,artist,album)+' [JuK]';
            Popen(['dcop', port, 'default', 'say', server, target, string]).communicate()
            sys.exit(0)
        else:
            if error:
                bad_apps.append('JuK')
            else:
                error = True
                bad_apps = ['JuK']

    kaffeine = check_running('kaffeine')
    if kaffeine:
        title = os.popen('dcop '+kaffeine+' KaffeineIface title').readline().rstrip('\n')
        artist = os.popen('dcop '+kaffeine+' KaffeineIface artist').readline().rstrip('\n')
        album = os.popen('dcop '+kaffeine+' KaffeineIface album').readline().rstrip('\n')

        if title:
            string=pretty_print(title,artist,album)+' [Kaffeine]'
            Popen(['dcop', port, 'default', 'say', server, target, string]).communicate()
            sys.exit(0)
        else:
            if error:
                bad_apps.append('Kaffeine')
            else:
                error = True
                bad_apps = ['Kaffeine']

    noatun = check_running('noatun')
    if noatun:
        string = os.popen('dcop '+noatun+' Noatun title').readline().rstrip('\n');

        if string:
            string=pretty_print(string)+' [Noatun]'
            Popen(['dcop', port, 'default', 'say', server, target, string]).communicate();
            sys.exit(0)
        else:
            if error:
                bad_apps.append('Noatun')
            else:
                error = True
                bad_apps = ['Noatun']

    yammi = check_running('yammi')
    if yammi:
        title = os.popen('dcop '+yammi+' YammiPlayer songTitle').readline().rstrip('\n')
        artist = os.popen('dcop '+yammi+' YammiPlayer songArtist').readline().rstrip('\n')
        album = os.popen('dcop '+yammi+' YammiPlayer songAlbum').readline().rstrip('\n')

        if title:
            string = pretty_print(title,artist,album)+' [Yammi]';
            Popen(['dcop', port, 'default', 'say', server, target, string]).communicate()
            sys.exit(0)
        else:
            if error:
                bad_apps.append('Yammi')
            else:
                error = True
                bad_apps = ['Yammi']

    kscd = check_running('kscd')
    if kscd:
        title = os.popen('dcop '+kscd+' CDPlayer currentTrackTitle').readline().rstrip('\n')
        artist = os.popen('dcop '+kscd+' CDPlayer currentArtist').readline().rstrip('\n')
        album = os.popen('dcop '+kscd+' CDPlayer currentAlbum').readline().rstrip('\n')
        kscdplaying = os.popen('dcop '+kscd+' CDPlayer currentAlbum').readline().rstrip('\n')

        if title and kscdplaying:
            string = pretty_print(title,artist,album)+' [kscd]';
            Popen(['dcop', port, 'default', 'say', server, target, string]).communicate()
            sys.exit(0)
        else:
            if error:
                bad_apps.append('kscd')
            else:
                error = True
                bad_apps = ['kscd']

    if not amarok and not juk and not kaffeine and not noatun and not yammi and not xmmsRunning and not kscd:
        os.popen("dcop %s default error \"No supported media player is running\""%(port))

    if bad_apps != None:
        error = ','.join(bad_apps)
        os.popen("dcop %s default error \"Nothing is playing in %s\""%(port,error))
        sys.exit(1)

