#!/usr/bin/perl
#
# cmhof - Shows where you are in the Cask Marque Beer drinkers 
# Hall of Fame you are. 
#
# Version 1.1 (C) 2015 Andrew Rawlins (awr-cmleader@fermit.org.uk)
#
# Please be considerate when using this script - Don't keep calling
# it - maybe call it from cron once a day and have it display when 
# you log in.
#
# Usage: perl cmhof [firstname:lastname]
#
# Leave [firstname:lastname] blank to show the entire hall of 
# fame.
#
# 1.0  Intial Release
# 1.1  Added the date to a single person query to allow graphing

use LWP::Simple;
use HTML::TableExtract;
use POSIX 'strftime';

my $url = "http://cask-marque.co.uk/beer-drinkers/hall-fame/";
my $title_line = 0;
my $name = @ARGV[0];

my $content = get $url;
die "Couldn't get $url" unless defined $content;

$te = new HTML::TableExtract;
$te->parse($content);

# We assume the page onlyhas the leaderboard ..
foreach $ts ($te->tables) {
    foreach $row ($ts->rows) {

        ($rank, $lname, $fname, $score) = @$row;

	if ($title_line == 1 ) {
		$top_score = $score;
	}

	if (defined($name)) {

		@p_name = split(/:/, $name);
		($p_lname, $p_fname) = @p_name;

		if ($p_fname eq $fname) {

			my $date = strftime '%Y%m%d', localtime;

			if ($p_lname eq $lname) {
				$away_num = ($top_score - $score);
				print $date . ":" . $rank . ":" . $score . ":" . $away_num . ":" . $top_score . "\n";
			}
		}

		# We could exit here but we might have a few 'Jones' so we carry on
	
	} else {
	
	        if ($title_line < 2 ) {
       			print "+-------+---------------------+---------------------+-----------------+\n";
        	}

		printf "| %-5s | %-19s | %-19s | %-15s |\n", $rank, $lname, $fname, $score; 

	}

	$title_line++;


    }
}

if (!defined($p_lname)) {
	print "+-------+---------------------+---------------------+-----------------+\n";
}
