# Copyright (c) 2006 Torbjörn Svensson <azoff@se.linux.org>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

use Irssi;
use strict;
use IO::Socket;
use vars qw/$VERSION %IRSSI/;

$VERSION = '1.0';
%IRSSI = {
    authors     => 'Torbjörn \'Azoff\' Svensson',
    contact     => 'azoff@se.linux.org',
    name        => 'irssi-mpc.pl',
    description => 'Display mpd data using /np [arg]',
    license     => 'GPL',
    changed     => '2006-10-15'
};

# default values
Irssi::settings_add_str('misc', 'mpd_host', 'localhost');
Irssi::settings_add_int('misc', 'mpd_port', '6600');
Irssi::command_bind('np', 'cmd_get_mpd_info');

sub cmd_get_mpd_info {
	my ($args, undef) = @_;
	my ($host)   = Irssi::settings_get_str('mpd_host');
	my ($port)   = Irssi::settings_get_int('mpd_port');
	my ($data)   = {};
	my ($id)     = 0;
	my ($outstr) = "";

	my $socket   = IO::Socket::INET->new(
			PeerAddr => $host,
			PeerPort => $port,
			Proto    => "tcp",
			Type     => SOCK_STREAM,
		); #or Irssi::print("Unable to connect $host:$port, $@") and return;

	# IO::Socket::INET returns undef upon error
	if(not defined($socket)) {
		Irssi::print("Unable to connect $host:$port, $@");
		return; # do not use die here as die will unload script (could be a temporary failure!)
	}

	
	# get the generic info
	print $socket "status\n";

	while (<$socket>) {
		chomp;
		last if ($_ =~ /^OK$/);
		if (/^ACK/) {
			Irssi::print("Error: $_");
			return;
		}

		if (/^bitrate: (\d+)$/) {
			$data->{"bitrate"} = $1;
		} elsif (/^audio: (\d+):(\d+):(\d+)$/) {
			$data->{"frequency"} = $1;
			$data->{"bits"} = $2;
			$data->{"channels"} = $3
		} elsif (/^time: (\d+):(\d+)$/) {
			$data->{"cur_time"} = $1;
			$data->{"tot_time"} = $2;
		} elsif (/^state: (\w+)$/) {
			$data->{"state"} = $1;
		} elsif (/^playlist: (\d+)$/) {
			$data->{"playlist"} = $1;
		} elsif (/^songid: (\d+)$/) {
			$id = $1;
		}
	}
	
	if ($data->{"state"} !~ /stop/) {
		# get the song specefik info
		print $socket "playlistinfo $id\n";

		while (<$socket>) {
			chomp;
			last if (/^OK$/);
			if (/^ACK/) {
				Irssi::print("Error: $_");
				return;
			}

			if (/^Artist: (.+)$/) {
				$data->{"artist"} = $1;
			} elsif (/^Title: (.+)$/) {
				$data->{"title"} = $1;
			} elsif (/^file: (.+)$/) {
				$data->{"file"} = $1;
			}
		}

		# do the fancy string
		$data->{"cur_time_str"} = sprintf("%d:%.2d", $data->{cur_time}/60, $data->{cur_time} % 60);
		$data->{"tot_time_str"} = sprintf("%d:%.2d", $data->{tot_time}/60, $data->{tot_time} % 60);

		if ($args=~/^\w+$/) {
			$outstr = "$args ";
		} else {
			$outstr = "is listening to ";
		}

		if (length($data->{"artist"} . $data->{"title"})) {
			$outstr .= sprintf("%s - %s", $data->{"artist"}, $data->{"title"});
		} elsif ($data->{"file"} =~ /([^\/]+)$/) {
			$outstr .= $1;
		} else {
			$outstr .= $data->{"file"};
		}
		
		if ($data->{"tot_time"} == 0) {
			$outstr .= sprintf(" [%s]", $data->{"cur_time_str"});
		} else {
			$outstr .= sprintf(" [%s/%s ♫ %dkbps]", $data->{"cur_time_str"}, $data->{"tot_time_str"}, $data->{"bitrate"});
		}

	} else {
		# not playing..
		$outstr = "is not playing anything right now.";
	}

	# close the connection
	print $socket "close\n";
	close($socket);

	# put the result into active window
	Irssi::active_win()->command("/me $outstr");
}


