#! /usr/bin/perl
use strict;
use warnings;
use Date::Manip;

# Parses tournament results from the DDR Europe result list

my $season = shift;
my $name;
die "Missing season (give on command line)." if (!defined($season));

print "begin;\n";

while (<>) {
	if (/<h2> \s* (.*?) \s* <\/h2>/x) {
		$name = $1;
		next;
	}
	if (/<br>Country: \s* (.*?) \s*
             <br>Location: \s* (.*?) \s*
             <br>Date: \s* (.*?) \s*
             <br>Mix: \s* (.*?) \s*
             <br>ScoringSystem: \s* (.*?) \s* <br>
            /x) {
		my ($country, $location, $date, $mix, $system) = ($1, $2, $3, $4, $5);
		$mix =~ s/Euromix/EuroMix/;

		print "INSERT INTO tournaments \n";
		print "  (season, name, country, location, \"date\", machine, scoringsystem) VALUES (\n";
		print "    (SELECT season FROM seasons WHERE name='$season'),\n";
		print "    '$name',\n";
		print "    (SELECT country FROM countries WHERE name='$country'),\n";
		print "    '$location',\n";
		printf "    '%s',\n", Date::Manip::UnixDate($date, '%Y-%m-%d');
		print "    (SELECT machine FROM machines WHERE name='$mix'),\n";
		print "    (SELECT scoringsystem FROM scoringsystems WHERE name='$system')\n";
		print ");\n";
	}
}

printf "commit;\n";
