package XAMP;

use strict;
use warnings;

use Milkbone;

my $commit = 0;
my $last_text = "";

#
# Some rather kludgy OS-specific code follows
#


if($^O =~ /Win32/)
{
    eval '
	package XAMP;

        use Win32::GuiText qw(FindWindowLike GetWindowText);

        sub get_text
        {
            my ($win) = FindWindowLike(0, "", "Winamp v1.x");
            ($win) = FindWindowLike(0, "", "STUDIO") unless $win;

            my $song = GetWindowText($win) if $win;
            
            $song = $song x 2 unless($song =~ m/\d*\. (.*)- Winamp/);
            return $song;
 	}
    ';
}
else
{
    eval '
        use Xmms::Remote;

	my $rem = Xmms::Remote->new;
	
	sub get_text
	{
		my $text = $rem->get_playlist_title($rem->get_playlist_pos);
		$commit = 1 if $text ne $last_text;
		return $text;
	}
    ' or die $@;
}

sub get_title
{
	my $text = get_text();
	my ($title) = $text =~ /-\s+(.*)/;
	return $title || "Nothing";
}

sub get_artist
{
	my $text = get_text();
	my ($artist) = $text =~ /(.*?)\s+-/;
	return $artist || "Nobody";
}

sub update
{
    my ($text) = get_text();
    return if $text eq $last_text;
    $last_text = $text;

    my ($artist, $title) = (get_artist(), get_title());
    hook('protocol_mod_prof', -name => '%a', -value => $artist);
    hook('protocol_mod_prof', -name => '%s', -value => $title);
    
    hook('protocol_mod_away', -name => '%a', -value => $artist);
    hook('protocol_mod_away', -name => '%s', -value => $title);

    hook("protocol_commit_info") if $commit;
}

register_hook("signed_in", sub {
	update();
	
	hook("tk_getmain")->repeat(5000, sub {
		update();
		$commit = 0;
	});
	
});