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

# Parses tournament results from the DDR Europe result list

my $season = shift;
my ($name, $round, $group, $player, $position, @rsongs);
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/;
		$mix =~ s/Dance Dance Revolution 8th mix - Extreme/DDR Extreme/;
		$system = '10K Machine score' if ($system =~ /^\s*$/);

		print "INSERT INTO tournaments \n";
		print "  (season, tournamentname, country, location, \"date\", machine, scoringsystem) VALUES (\n";
		print "    (SELECT season FROM seasons WHERE seasonname='$season' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
		print "    '$name',\n";
		print "    (SELECT country FROM countries WHERE countryname='$country'),\n";
		print "    '$location',\n";
		printf "    '%s',\n", Date::Manip::UnixDate($date, '%Y-%m-%d');
		print "    (SELECT machine FROM machines WHERE machinename='$mix'),\n";
		print "    (SELECT scoringsystem FROM scoringsystems WHERE scoringsystemname='$system')\n";
		print ");\n";
	}
	
	# Player's results (header)
	if (/^ <tr><td \s* class=dtd> .*? class="link"> (.*?) <\/a> $/x) {
		$player = $1;

		printf "INSERT INTO roundparticipation (tournament, round, parallel, player, position) VALUES (\n";
		print "   (SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
		print "   $round, $group,\n";
		print "   (SELECT player FROM players WHERE nick='$player'),\n";
		print "   $position\n";
		print ");\n";
		++$position;
	}

	# Player's results (score)
	if (/<td \s* class=dtd (?: m | song ) >/x) {
		my $i = 0;

		# random songs
		while (s/<td \s* class=dtdm> (\d+) <\/td>//x) {
			printf "INSERT INTO scores (tournament, round, parallel, player, songnumber, song, chosen, score) VALUES (\n";
			print "   (SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
			print "   $round, $group,\n";
			print "   (SELECT player FROM players WHERE nick='$player'),\n";
			print "   $i,\n";
			print "   (SELECT song FROM songs WHERE lower(title)=lower('$rsongs[$i]')),\n";
			print "   'f',\n";
			print "   $1);\n";
			++$i;
		}

		# chosen songs
		while (s/<td \s* class=dtdsong> .*? class="link"> (.*?) <\/a> .*? <td \s* class=dtdscore> (\d+) <\/td>//x) {
			my $song = song_map($1);
			my $score = $2;
			$song =~ s/'/\\'/g;
		
			printf "INSERT INTO scores (tournament, round, parallel, player, songnumber, song, chosen, score) VALUES (\n";
			print "   (SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
			print "   $round, $group,\n";
			print "   (SELECT player FROM players WHERE nick='$player'),\n";
			print "   $i,\n";
			print "   (SELECT song FROM songs WHERE lower(title)=lower('$song')),\n";
			print "   't',\n";
			print "   $score);\n";
			++$i;
		}
	}

	# New round
	if (/<h3 \s* class=dthr> Round \s* (\d+) \s* <\/h3>/x) {
		$round = $1;

		print "INSERT INTO rounds (tournament, round, randomsongs, chosensongs) \n";
		print "  VALUES (\n";
		print "   (SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
		print "   $round,\n";
		print "   0, 0);\n";  # Don't worry, we'll fix it later :-P
	}
	
	# New group, and the random songs for it
	if (/<th \s* class=dthp> ( Players | Group \s* (\d+) )<\/th>/x) {
		# bit of an evil hack here
		$group = $2;
		$group = 0 if ($1 eq 'Players');

		$position = 1;

		print "INSERT INTO groups (tournament, round, parallel) VALUES (\n";
		print "   (SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
		print "   $round, $group);\n";

		# Find the random songs, if any
		@rsongs = ();

		while (s/<th \s* class=dthpsong> .*? "color:white"> (.*?) <\/a><\/th>//x) {
			my $song = song_map($1);
			$song =~ s/'/\\'/g;
		
			push @rsongs, $song;

			print "INSERT INTO roundrandomsongs (tournament, round, parallel, song) VALUES (\n";
			print "   (SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
			print "   $round, $group,\n";
			print "   (SELECT song FROM songs WHERE lower(title)=lower('$song'))\n";
			print ");\n";
		}

		# Correct the random songs in the table
		printf "UPDATE rounds SET randomsongs=%u WHERE \n", scalar @rsongs;
		print "  tournament=(SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )) AND \n";
		print "  round=$round;\n";
	}

	# Header for chosen song (evil)
	if (/<th \s* class=dthp \s* colspan=2>&nbsp<\/th>/x) {
		printf "UPDATE rounds SET chosensongs=1 WHERE \n";
		print "  tournament=(SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )) AND \n";
		print "  round=$round;\n";
	}

	# First place
	if (/A \s* well-earned \s* victory \s* for .*? class="link"> (.*?) <\/a> (?: , \s* who \s* got \s* (\d+) \s* point )?/x) {
		my $nick = $1;
		my $points = $2;

		# Whoa :-)
		$points = 'NULL' unless defined($points);

		# Woot, evil
		printf "INSERT INTO players SELECT nextval('players_player_seq') AS player, '%s' AS nick, ( SELECT country FROM countries WHERE countryname='Norway' ) AS country WHERE '%s' NOT IN ( SELECT nick FROM players );\n", $nick, $nick;
		
		print "INSERT INTO tournamentrankings (tournament, ranking, player, points) VALUES (\n";
		print "   (SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
		print "   1,\n";
		print "   (SELECT player FROM players WHERE nick='$nick'),\n";
		print "   $points);\n";
	}

	# Odd split first places and stuff
	if (/^ \s+ ( .*? \s+ and \s+ .*? <\/a>) \s+ won/x) {
		my $winners = $1;
		while ($winners =~ s/<a \s+ href= .*? class="link"> (.*?) <\/a>//x) {
			my $nick = $1;
			my $points = 'NULL';

			printf "INSERT INTO players SELECT nextval('players_player_seq') AS player, '%s' AS nick, ( SELECT country FROM countries WHERE countryname='Norway' ) AS country WHERE '%s' NOT IN ( SELECT nick FROM players );\n", $nick, $nick;
			
			print "INSERT INTO tournamentrankings (tournament, ranking, player, points) VALUES (\n";
			print "   (SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
			print "   1,\n";
			print "   (SELECT player FROM players WHERE nick='$nick'),\n";
			print "   $points);\n";
		}
	}

	# All other places
	while (s/(\d+) (?: st | nd | rd | th ) \s* place: .*? class="link"> (.*?) <\/a> \s* (?: got \s* (\d+) \s* point )?//x) {
		my $ranking = $1;	
		my $nick = $2;
		my $points = $3;

		# Whoa :-)
		$points = 'NULL' unless defined($points);

		# Woot, evil
		printf "INSERT INTO players SELECT nextval('players_player_seq') AS player, '%s' AS nick, ( SELECT country FROM countries WHERE countryname='Norway' ) AS country WHERE '%s' NOT IN ( SELECT nick FROM players );\n", $nick, $nick;
		
		print "INSERT INTO tournamentrankings (tournament, ranking, player, points) VALUES (\n";
		print "   (SELECT tournament FROM tournaments WHERE tournamentname='$name' AND season=( SELECT season FROM seasons WHERE seasonname='$season' )),\n";
		print "   $ranking,\n";
		print "   (SELECT player FROM players WHERE nick='$nick'),\n";
		print "   $points);\n";
	}	
}

printf "commit;\n";

# different names for songs
sub song_map {
	my $song = shift;

	$song =~ s/Paranoia -Rebirth-/PARANOiA Rebirth/;
	$song =~ s/The Center of the heart/The Centre of the Heart (Stonebridge Club Mix)/;
	$song =~ s/Can't stop falling in love/Can't Stop Fallin' in Love/;
	$song =~ s/B4U -B4 ZA Beat Mix-/B4U (B4 Za Beat Mix)/;
	$song =~ s/Jam Jam Reggae/Jam Jam Reggae (AM Swing Mix)/;
	$song =~ s/Trip Machine -Climax-/Trip Machine Climax/;
	$song =~ s/Dont try to stop it/Don't Try to Stop It/;
	$song =~ s/Healing Vision -AM-/Healing Vision (Angelic Mix)/;
	$song =~ s/5,6,7,8/5, 6, 7, 8/;
	$song =~ s/Keep On Movin/Keep On Movin'/;
	$song =~ s/So Deep/So Deep (Perfect Sphere Mix)/;
	$song =~ s/Aarons Party/Aaron's Party (Come Get It)/;
	$song =~ s/Candy \*/Candy\xe2\x98\x86/;
	$song =~ s/www\.blondie girl/www.blonde girl (MOMO Mix)/;
	$song =~ s/DXY/DXY!/;
	$song =~ s/Burning the floor/Burnin' the Floor/;
	$song =~ s/Never Gonna Make/Never Gonna Make (Factory Team Mix)/;
	$song =~ s/Max300/Max 300/;
	$song =~ s/Era/era (nostalmix)/;
	$song =~ s/Electro Tuned/Electro Tuned (the SubS Mix)/;
	$song =~ s/Make a Jam/Make A Jam!/;
	$song =~ s/Paranoia KCET -clean mix-/Paranoia KCET (Clean Mix)/;
	$song =~ s/Cant Stop -Speed Mix-/Can't Stop Fallin' in Love (SPEED MIX)/;
	$song =~ s/Love This Feelin/Love This Feelin'/;
	$song =~ s/Trip Machine -Luv mix-/Trip Machine (Luv Mix)/;
	$song =~ s/Let The Beat Hit Them/Let the Beat Hit 'em!/;
	$song =~ s/Luv To Me/Luv to Me (AMD Mix)/;
	$song =~ s/20 November/20th November/;

	$song =~ s/Love Shine/LOVE \xe2\x9d\xa4 SHINE/;
	$song =~ s/Long Train Running/LONG TRAIN RUNNIN'/;
	$song =~ s/Door of Magic/Mahou no Tobira (Theme Of Space Maco) [Door of Magic]/;
	$song =~ s/True -trance sunrise mix-/true... ~trance sunrise mix~/;
	$song =~ s/Rhythm and Police/RHYTHM AND POLICE (K.O.G G3 Mix)/;
	$song =~ s/Burnin the floor -momo mix-/BURNIN' THE FLOOR (MOMO MIX)/;
	$song =~ s/Senorita -speedy mix-/SENORITA (Speedy Mix)/;
	$song =~ s/Drop out -remix-/DROP OUT (FROM NONSTOP MEGAMIX)/;
	$song =~ s/57 metallic gray/Heaven is a '57 metallic gray (gimmix)/;
	$song =~ s/Brilliant 2 U/BRILLIANT 2U/;
	$song =~ s/Blue Impulse/Aoi Shoudou (for EXTREME) [Blue Impulse]/;
	$song =~ s/Sobakasu \(Freckles\)/SOBAKASU FRECKLES/;
	$song =~ s/Synchronized Love/SYNCHRONIZED LOVE (Red Monster Hyper Mix)/;
	$song =~ s/Orion\.78 -civ mix-/ORION .78 (civilization mix)/;

	return $song;
}
