#!/usr/bin/perl

# Copyright (c) 2005-2007 Tuukka Lukkala
# tlukkala ät gmail d0t com
# http://tuukka.shelli.fi/irssi/

# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies or substantial
# portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# amaroknp.pl (1.4)
# This is a simple script for irssi which (attempts to) show the song played by amaroK
# in the active channel or query window. It should output something like this:
# <@mynick> np: Artist - Song [1:34/4:05]. Optionally it can also display bitrate,
# album name, release year, progressbar and streaming media url.

# USAGE:
# /amarok
# /amarok <next/pause/stop/play/rand>

# CONFIGURATION:
# Check the configurable variables section below

# CHANGELOG:
# 1.3 -> 1.4
# -Added option to show album name and release year (requested by "theentity")
# 1.2 -> 1.3
# -Might require a fairly recent version of amarok (1.4 series)
# -Fixed time stats for files longer than 1 hr (thanks for the hint "bene")
# -Clean-up
# 1.1 -> 1.2
# -Fixed "showing bitrate when none available"
# -Other small fixes
# 1.0 -> 1.1
# -Fixes for streaming media (patch by "Spike Spiegel", thanks!)
#   -Fixed division by zero for streams
#   -New option to show streaming radio url
#   -Code clean-up
# -Showing time stats/progress bar for streams is pretty pointless, IMO, so I limited them for local files only
# -Added some controls (only the ones I found useful, it's easy to add your own if you want)
# -Converted to conform to X-Chat 2 perl interface

use strict;

Xchat::register("amaroknp","1.4","Now playing script for Amarok");
Xchat::print("\namaroknp 1.4 for X-Chat loaded\nCheck script for configuration\nUsage: /amarok\n");
Xchat::hook_command("amarok", "cmd_amaroknp");

sub cmd_amaroknp {
	# CONFIGURABLE VARIABLES
	my $dcopbin = "dcop";		# Adjust this to the full path of dcop if it's not in your PATH.
					# eg. /opt/kde/bin/dcop
	my $mode = "action";		# Set to message (/msg) or action (/me)
	my $showtime = 1;		# Set to 1 to enable time stats
	my $showprogress = 1;		# Set to 1 to enable progressbar
	my $showbitrate = 1;		# Set to 1 to enable bitrate info
	my $showremoteurl = 1;		# Set to 1 to show streaming radio address
	my $showalbum = 1;		# Set to 1 to show album name
	my $showyear = 1;		# Set to 1 to show release year
	# OTHER VARIABLES
	my $playing; 			# Whether amaroK is playing something or not
	my $song; 			# The song currently playing
	my $timenow;			# Current position in the song, raw
	my $timetotal;			# Total length of teh song, raw
	my $timenowFormat;		# Current position in the song, formatted
	my $timetotalFormat;		# Total length of the song, formatted
	my $output;			# The format in which all this is going -> channel
	my $amaroktest;			# To see if amarok is running or not
	my $amarokNOTrunning;		# Don't ask me.. :z
	my $progressbar;		# Progressbar [|||||||--]
	my $bitrate;			# Bitrate
	my $albumname;			# Album name
	my $year;			# Release year
	my $perc;			# $timenow / $timetotal (for progressbar)
	my $isremotesource;		# Wether current song is a streaming source or a remote one anyway
	my $encodedURL;			# Url to the music source
	my $random;			# Random mode enabled/disabled?
	my $data = $_[0][1];		# Possible parameters

	# Let's check if we have dcop..
	if (!`$dcopbin`) {
		Xchat::print("Couldn't find dcop executable.. Make sure dcop is in your PATH or edit dcopbin in the script");
		return 1;
	}

	# ..and if amaroK is running
	$amaroktest = `$dcopbin amarok 2> /dev/null`;
	chomp($amaroktest);
	if ($amaroktest =~ s/^$/No such application: 'amarok'/) {
		Xchat::print("amaroK isn't running?");
		$amarokNOTrunning="nope";
		return 1;
	}
	if (!$amarokNOTrunning) {
		# If control parameters were passed (/amarok something)
		if ($data) {
			if ($data eq "next") {
				`$dcopbin amarok default next`;
				return 1;
			}
			elsif ($data eq "pause") {
				`$dcopbin amarok default playPause`;
				return 1;
			}
			elsif ($data eq "stop") {
				`$dcopbin amarok default stop`;
				return 1;
			}
			elsif ($data eq "play") {
				`$dcopbin amarok default play`;
				return 1;
			}
			elsif ($data eq "rand") {
				chomp($random = `$dcopbin amarok default randomModeStatus`);
				if ($random eq "false") {
					`$dcopbin amarok default enableRandomMode 1`;
					Xchat::print("Random mode enabled");
					return 1;
				}
				else  {
					`$dcopbin amarok default enableRandomMode 0`;
					Xchat::print("Random mode disabled");
					return 1;
				}
			}
			else {
				Xchat::print("Unrecognized command or whitespace after command.");
				return 1;
			}
		}
		else {
			chomp($playing = `$dcopbin amarok default isPlaying`);
			if ($playing eq "false") {
				Xchat::print("amaroK isn't playing anything?");
				return 1;
			}
			else {
				# Get some infos
				chomp($song = `$dcopbin amarok default nowPlaying`);
				chomp($encodedURL = `$dcopbin amarok default encodedURL`);
				$isremotesource = $encodedURL =~ m/http/; 
				# Get time information if configured to do so
				if (($showtime eq 1) || ($showprogress eq 1)) {
					if (!$isremotesource) {
						if ($showprogress eq 1) {
							chomp($timenow = `$dcopbin amarok default trackCurrentTime`);
							chomp($timetotal = `$dcopbin amarok default trackTotalTime`);
						}
						if ($showtime eq 1) {
							chomp($timenowFormat = `$dcopbin amarok default currentTime`);
							chomp($timetotalFormat = `$dcopbin amarok default totalTime`);
						}
					}
					else {
						# We don't need time stats or progressbar if source is a stream
						$showprogress = 0;
						$showtime = 0;
					}
				}
				if ($showprogress eq 1) {
					$progressbar = "[||||||||||]";
					$perc = sprintf("%.1f",$timenow/$timetotal)*10;
					$progressbar = "["."|"x$perc."-"x(10-$perc)."]";
				}
				if ($showbitrate eq 1) {
					chomp($bitrate = `$dcopbin amarok default bitrate`);
					# Don't show bitrate if it isn't available
					if ($bitrate eq "?") {
						$showbitrate = 0;
					}
					$bitrate = $bitrate . " kbps";
				}
				if ($showalbum eq 1) {
					chomp($albumname = `$dcopbin amarok default album`);
					if (length($albumname) < 1) {
						$showalbum = "no";
					}
				}
				if ($showyear eq 1) {
					chomp($year = `$dcopbin amarok default year`);
					if ($year eq 0) {
						$showyear = "no";
					}
				}
				# The way it's gonna show up when we do /amarok
				if ($mode eq "message") {
					$output = "np:";
				}
				elsif ($mode eq "action") {
					$output = "spielt grade";
				}
				else {
					Xchat::print("$mode isn't a valid output mode!\nuse either message or action");
					return 1;
				}
				$output = $output . " " . $song;
				if ($showalbum eq 1) {
					$output = $output . ", von " . $albumname;
				}
				if ($showyear eq 1) {
					$output = $output . " (" . $year . ")";
				}
				if ($showtime eq 1) {
					$output = $output . " " . "[$timenowFormat/$timetotalFormat]";
				}
				if ($showbitrate eq 1) {
					$output = $output . " " . "[$bitrate]";
				}
				if ($showremoteurl eq 1 && $isremotesource) {
					$output = $output . " " . "[Streaming: $encodedURL ]";
				}
				if ($showprogress eq 1) {
					$output = $output . " " . $progressbar;
				}
			}
			if ($output) {
				if ($mode eq "message") {
					Xchat::command("say $output");
					return 1;
				}
				elsif ($mode eq "action") {
					Xchat::command("me $output");
					return 1;
				}
			}
		}
	}
}
