#!/usr/bin/env perl
# 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

use strict;
use warnings;

my $port=shift;
my $server=shift;
my $target=shift;

# Variables
my $amarok;
my $kaffeine;
my $juk;
my $noatun;
my $title;
my $artist;
my $album;
my $error;

sub check_running 
{
    my $application=shift;
    
    if (`dcop $application`)
    {
	return 1;
    }
    else
    {
	return 0;
    }
}

sub pretty_print
{
    my $title=shift;
    my $artist=shift;
    my $album=shift;

    if(!is_empty($artist) && !is_empty($album))
    {
	return "/me is playing \"$title\" by $artist on $album";
    }
    elsif(!is_empty($artist))
    {
	return "/me is playing \"$title\" by $artist";
    }
    elsif(!is_empty($album))
    {
	return "/me is playing \"$title\" on $album";
    }
    else
    {
	return "/me is playing $title";
    }
}

sub is_empty
{
    my $string=shift;
    
    if($string =~ /\S/)
    {
	return 0;
    }
    else
    {
	return 1;
    }
}

$amarok=check_running("amarok");
$juk=check_running("juk");
$kaffeine=check_running("kaffeine");
$noatun=check_running("noatun");

if($amarok)
{
    # Old amaroK interface
    $title=`dcop amarok player title`;
    
    if(is_empty($title))
    {
	# New amaroK interface
	$title=`dcop amarok playlist title`;
	$artist=`dcop amarok playlist artist`;
        $album=`dcop amarok playlist album`;
    }
    else
    {	
	$artist=`dcop amarok player artist`;
	$album=`dcop amarok player album`;
    }
    
    chomp $title;
    chomp $artist;
    chomp $album;

    if(!is_empty($title))
    {
	my $string=pretty_print($title,$artist,$album);
	exec 'dcop', $port, 'Konversation', 'say', $server, $target, $string;
    }
    else
    {
	$error="amaroK";
    }
}

if($juk)
{
    my $string=`dcop juk Player playingString`;
    chomp $string;

    if(!is_empty($string))
    {
        exec 'dcop', $port, 'Konversation', 'say', $server, $target, "/me is playing $string";
    }
    else
    {
	$error=join(',',$error,"JuK");
    }
}

if($kaffeine)
{
    my $string=`dcop kaffeine KaffeineIface title`;
    chomp $string;
    
    if(!is_empty($string))
    {
	exec 'dcop', $port, 'Konversation', 'say', $server, $target, "/me is playing $string";
    }
    else
    {
	$error=join(',',$error,"Kaffeine");
    }
}

if($noatun)
{
    my $string=`dcop noatun Noatun title`;
    chomp $string;

    if(!is_empty($string))
    {
	exec 'dcop', $port, 'Konversation', 'say', $server, $target, "/me is playing $string";
    }
    else
    {
        $error=join(',',$error,"Noatun");
    }
}

if(!$amarok && !$juk && !$kaffeine && !$noatun)
{
	exec 'dcop', $port, 'Konversation', 'error', 'No supported media player is running';
}

if($error)
{
	exec 'dcop', $port, 'Konversation', 'error', "Nothing is playing in $error";
}
