#!/usr/bin/perl -w

# This script is distributed under GNU/GPL
# It was originaly written by SpideR <spider312@free.fr>
# Infos aviable on http://www.spider-serv.net
# Help aviable on irc://irc.spider-serv.net - #bnc
#
# This script displays the song currently played in MPD
# It uses mpc (aviable on http://www.musicpd.org and in your package manager)
# The script run `mpc` and parse result to fill variables, and /me those varaibles
# It was tested under version 0.11.2, and should not work with others, please report
# It's simplistic, but contrary to the others scripts, it works :(
#
# It's a pre-alpha version, as i never coded in Perl and never coded a XChat script
# Please repport bugs
#
# REQUIRES MPC !

IRC::register("MPD Announce","0.1","","");
IRC::print "SpideR's MPD Announcer loaded";
IRC::add_command_handler("mpc","mpc");
Xchat::hook_command("mpc-full","mpc",["full"]);

sub mpc
{
	# Arguments
	$disp = shift;
	# Variables
	$title = '' ;
	$infos = '' ;
	$else = '' ;
	$status = '' ;
	$playlist = '' ;
	$time_elapsed = '' ;
	$time_percent = '' ;
	$volume = '' ;
	$repeat = '' ;
	$random = '' ;
	$disp_title = '' ;
	$disp_info = '' ;
	$disp_else = '' ;

	# Run command
	$out = `mpc --format %title%`;
	chop ($out);

	if ( $out =~ /^(.*)\n(.*)\n(.*)/ ) { # Normal case : there is 3 lines in the output
		$title = $1 ;
		$infos = $2 ;
		$else = $3 ;
		$disp_title = $title ;
		# Parsing line 2
		if ( $infos =~ /\[(.*)\]\ *\#(.*) (.*) \((.*)\)/) {
			$status = $1 ;
			$playlist = $2 ;
			$time_elapsed = $3 ;
			$time_percent = $4 ;
			$disp_info = " (Playlist : $playlist) - [Time elapsed : $time_elapsed - $time_percent]"
		}
		# Parsing line 3
		if ( $else =~ /volume: (.*)   repeat: (.*)   random: (.*)/ ) {
			$volume = $1 ;
			$repeat = $2 ;
			$random = $3 ;
			$disp_else = " - {Volume : $volume}" ;
		}
		$text = '\'mpd is '.$status ;
		$text .= ' "'.$title.'" ' ;
		if ( $disp eq 'full' ) {
			$text .= $disp_info.$disp_else ;
		}
		IRC::command("/me 's".$text) ;
	} elsif ( $out =~ /volume:(.*)   repeat: (.*)   random: (.*)/ ) { # Stoped case
		$volume = $1 ;
		$repeat = $2 ;
		$random = $3 ;
		IRC::command("/me 's MPD is stopped") ;
	} else { # Lines can't be separated : there is less than 3 lines
		IRC::command("/echo Something gone wrong with /mpc :(") ;
		IRC::command("/echo [$out]") ;
	}
	return 1;
}
