#! /usr/bin/perl

use strict;
use vars qw/
	$HELP $VERBOSE $VERSION $EXIT_STATUS $DEBUG
	$SLEEP_INTERVAL $INFO $HANDSHAKE_INTERVAL
	$USER $PASS
	/;
use Carp;
use Audio::Scrobbler;

use File::Basename;
use Getopt::Long;
Getopt::Long::Configure("no_ignore_case");

GetOptions(
	'h|H|help|?' => \$HELP,
	"V|verbose" => \$VERBOSE,
	"D|debug" => \$DEBUG,
	"v|version" => \$VERSION,
	"s|sleep_interval=i" => \$SLEEP_INTERVAL,
	"info" => \$INFO,
	"user=s" => \$USER,
	"pass=s" => \$PASS,
);

$VERSION = 1.0;

if ($HELP) {
	usage();
	exit 0;
}

if (!$USER || !$PASS) {
	print STDERR "Cannot do anything without your username and password\n";
	usage();
	exit -1;
}

$SLEEP_INTERVAL = $SLEEP_INTERVAL ? $SLEEP_INTERVAL : 60;
$HANDSHAKE_INTERVAL = $HANDSHAKE_INTERVAL ? $HANDSHAKE_INTERVAL : 180;


my %configuration;
$configuration{progname} = "tst"; #"RDU90 Scrobbler";
$configuration{progver} = $VERSION;
$configuration{username} = $USER;
$configuration{password} = $PASS;
if ($VERBOSE) {
	$configuration{verbose} = $VERBOSE;
}

my $play_info_program = "/usr/bin/mocp";
my $play_info_args = '--format "__%song__ __%artist__ __%album__ __%tt__ __%tl__"';

my $percentage_before_submission = .50;

while(2+2 == 4) {
	my $scrobbler = new Audio::Scrobbler(cfg => \%configuration);
	if ($scrobbler->handshake()) {
		if ($VERBOSE) {
			print STDERR "Handshake successful\n";
		}
		if ($VERBOSE) {
			print "Information gathering command: $play_info_program $play_info_args\n";
		}
		if ($INFO || $VERBOSE) {
			print "Starting...\n";
		}
		my $last_song;
		while(2+2==4) {
			my $play_info = `$play_info_program $play_info_args`;
			if ($play_info) {
				$play_info =~ m/__([^_]*)__ __([^_]*)__ __([^_]*)__ __([^_]*)__ __([^_]*)__/;
				my ($song, $artist, $album, $total_time, $time_left) = ($1, $2, $3, $4, $5);
				if ($last_song ne $song) {
					if ($VERBOSE) {
						print "Song: $song\nArtist: $artist\nAlbum: $album\nTotal/Left Time: $total_time/$time_left\n";
					}
					my @time_pieces = split(/:/, $total_time);
					#Assuming that we aren't going to listen to anything terribly long...like in days
					my $seconds = pop @time_pieces;
					my $minutes = pop @time_pieces;
					my $hours = pop @time_pieces;
					my $total_time_in_seconds = ($seconds + ($minutes * 60) + ($hours * 60 * 60));

					@time_pieces = split(/:/, $time_left);
					#Assuming that we aren't going to listen to anything terribly long...like in days
					$seconds = pop @time_pieces;
					$minutes = pop @time_pieces;
					$hours = pop @time_pieces;
					my $time_left_in_seconds = ($seconds + ($minutes * 60) + ($hours * 60 * 60));

					if ($total_time_in_seconds * $percentage_before_submission > $time_left_in_seconds) {
						if ($VERBOSE) {
							print STDERR "We've been playing $song by $artist over $percentage_before_submission percent submitting\n";
						}
						if ($scrobbler->submit({title => $song, artist => $artist, album => $album, 'length' => $total_time_in_seconds})) {
							$last_song = $song;
							if ($INFO || $VERBOSE) {
								printf STDERR ("Sucessfully submitted $artist/$album/$song @ %s \n", scalar(localtime));
							}
						} else {
							print STDERR "Failed submitting $artist/$album/$song\n";
							print STDERR $scrobbler->err(), "\n";
							last;
						}
					}
				}
			}
			sleep $SLEEP_INTERVAL;
		}
	} else {
		print STDERR "Handshake failure\n";
		sleep $HANDSHAKE_INTERVAL;
		print STDERR "Retrying handshake after $HANDSHAKE_INTERVAL seconds";
		$HANDSHAKE_INTERVAL *= 2;
	}
}

exit $EXIT_STATUS;

sub usage {
	use File::Basename;
	my $prog = basename($0);
	print <<EOHELP;
$prog [options] --user USERNAME --password PASSWORD

h, H, help, ?		These instructions
V, verbose		Print extra messages to the console during run
D, debug		Debugging mode
user			Username for last.fm (required)
pass			Password for last.fm (required)

s|sleep_interval	Time to sleep between checking for new music (defaults to 30 seconds)
info			Print informational messages (what we just scrobbled)

EOHELP
}





