package XAMP;

use strict;
use warnings;

use Milkbone;

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

#
# Some rather kludgy OS-specific code follows
#

my $code;

if($^O =~ /Win32/)
{

    $code = <<'END';
    package XAMP;

    use Win32::GuiTest 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/);
    
    $song =~ s/ - Winamp//g;
    $song =~ s/\d*\.\s*//g;
    $commit = 1 if $song ne $last_text;
    return $song;
}
1;
END
}
else
{
    $code = '
package XAMP;
use Xmms::Remote;

my $rem = Xmms::Remote->new;

sub get_text
{
    my $text = $rem->get_playlist_title($rem->get_playlist_pos);
    $commit = 1 if defined($text) && $text ne $last_text;
    return $text;
}
1;
    ';
}

# $code =~ s/\n|\r//g;
eval $code or die "$! $@ $^E";

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

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

sub update
{
    my $text = get_text();
    $text = 'Nobody - Nothing' unless defined($text);
    return if $text eq $last_text;
    $last_text = $text;

    my ($artist, $title) = (get_artist($text), get_title($text));
    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;
    });
    
});

1;