#! /usr/bin/perl

use ccbs;
use strict;
use warnings;

my $cgi = new CGI;
my $id = $cgi->param('id');

my $dbh = ccbs::db_connect();

my $tournament = $dbh->selectrow_hashref('SELECT * FROM tournaments NATURAL JOIN seasons NATURAL JOIN countries NATURAL JOIN machines NATURAL JOIN scoringsystems WHERE tournament=?', undef, $id);

my $rankings;
if ($tournament->{'country'} == 1) {
	$rankings = ccbs::db_fetch_all($dbh, 'SELECT ranking,nick || \' (\' || countrycode::varchar || \')\' AS nick,COALESCE(points,-1) AS points FROM tournamentrankings NATURAL JOIN players NATURAL JOIN countries WHERE tournament=? ORDER BY ranking', $id);
} else {
	$rankings = ccbs::db_fetch_all($dbh, 'SELECT ranking,COALESCE(nick || \' (\' || clubcode::varchar || \')\', nick) AS nick,COALESCE(points,-1) AS points FROM tournamentrankings NATURAL JOIN players NATURAL LEFT JOIN clubs WHERE tournament=? ORDER BY ranking', $id);
}

my $songs = ccbs::db_fetch_all($dbh, 'SELECT song,title FROM machinesongs NATURAL JOIN songs WHERE machine=? ORDER BY LOWER(title)', $tournament->{'machine'});

# Check if the last round is valid for closing (by checking if all scores
# entered are valid)
my $ref = $dbh->selectrow_hashref('SELECT COUNT(*) AS num_incomplete FROM scores WHERE tournament=? AND (song IS NULL OR playmode IS NULL OR difficulty IS NULL OR chosen IS NULL or score IS NULL)', undef, $tournament->{'tournament'});
my ($closing_valid,$finishing_valid);
$finishing_valid = 0;
if ($ref->{'num_incomplete'} == 0) {
	$closing_valid = 1;
} else {
	$closing_valid = 0;
}

# Check if this tournament is on the bigscreen or not.
my $ref = $dbh->selectrow_hashref('SELECT * FROM bigscreen.active_tournament');
my $bigscreen = ($ref->{'tournament'} == $id) ? 1 : 0;

my $active_groups;
if ($bigscreen) {
	# Find all groups currently shown on the bigscreen.
	$active_groups = ccbs::db_fetch_all($dbh, 'SELECT * FROM bigscreen.active_groups WHERE tournament=?', $id);
}

# Swoop all the data in in a big join, then order it over to quasi-sane Perl objects.
# (round -> parallel -> player -> songs -> title,chosen,score)
my $scores;
if ($tournament->{'country'} == 1) {
	$scores = ccbs::db_fetch_all($dbh,
	'SELECT round,parallel,position,playmode,difficulty,songnumber,player,nick || \' (\' || countrycode::varchar || \')\' AS nick,song,title,chosen,score FROM roundparticipation NATURAL JOIN players NATURAL JOIN countries NATURAL JOIN scores NATURAL LEFT JOIN songs WHERE tournament=? ORDER BY round,parallel,position,songnumber',
	$id);
} else {
	$scores = ccbs::db_fetch_all($dbh,
	'SELECT round,parallel,position,playmode,difficulty,songnumber,player,COALESCE(nick || \' (\' || clubcode::varchar || \')\', nick) AS nick,song,title,chosen,score FROM roundparticipation NATURAL JOIN players NATURAL JOIN scores NATURAL LEFT JOIN songs NATURAL LEFT JOIN clubs WHERE tournament=? ORDER BY round,parallel,position,songnumber',
	$id);
}

my @rounds = ();

my ($round, $parallel, $player) = (-1,-1,'');
for my $score (@$scores) {
	if ($score->{'round'} != $round) {
		$round = $score->{'round'};
		push @rounds, { round => $round, parallels => [], locked => 0 };
		$parallel = -1;
	}
	my $p = $rounds[$#rounds]->{'parallels'};
	if ($score->{'parallel'} != $parallel) {
		$parallel = $score->{'parallel'};
		push @$p, { parallel => $parallel, players => [], songs => [], num_songs => 0 };
		$player = '';

		if ($bigscreen) {
			# suboptimal, but heck :-)
			$p->[$#$p]->{'bigscreen'} = 0;
			for my $ag (@$active_groups) {
				if ($ag->{'round'} == $round && $ag->{'parallel'} == $parallel) {
					$p->[$#$p]->{'bigscreen'} = 1;
					last;
				}
			}
		}

		# Information on songs is not selected from roundrandomsongs etc.,
		# but is filled in the first time the song is seen for this round
		# (ie. below)
	}
	if ($score->{'position'} == 1) {
		if ($score->{'chosen'}) {
			push @{$p->[$#$p]->{'songs'}}, { song => -1, title => '' };
		} else {
			push @{$p->[$#$p]->{'songs'}}, $score;
		}
		$p->[$#$p]->{'num_songs'}++;
	}
	
	my $pl = $p->[$#$p]->{'players'};
	if ($score->{'nick'} ne $player) {
		$player = $score->{'nick'};
		push @$pl, { player => $score->{'player'}, nick => $player, songs => [], total => 0, rank => 1 };
	}

	push @{$pl->[$#$pl]->{'songs'}}, $score;

	if (defined($score->{'score'})) {
		$pl->[$#$pl]->{'total'} += $score->{'score'};
	}
}

# Find the rank of all the players in every group, via simple insertion-like
# sort
for my $r (@rounds) {
	for my $p (@{$r->{'parallels'}}) {
		my $pls = $p->{'players'};
		for my $i (0..$#$pls) {
			my $rank = 1;
			for my $j (0..($i-1)) {
				if ($pls->[$i]->{'total'} < $pls->[$j]->{'total'}) {
					$pls->[$i]->{'rank'}++;
				} elsif ($pls->[$i]->{'total'} > $pls->[$j]->{'total'}) {
					$pls->[$j]->{'rank'}++;
				}
			}
		}
	}
}

# FIXME: In some odd cases, there _might_ be an empty group right at the end. Fix this when
#        we are able to add/delete people in groups.

my $num_rounds = scalar @rounds;
my $num_rankings = scalar @$rankings;

# Lock all rounds but the last (active?) one
for my $r (0..$#rounds-1) {
	$rounds[$r]->{'locked'} = 1;
}

# If there's only one group left and it's valid for closing, we can also finish
# the entire tournament if we'd like
if ($closing_valid && (scalar @rounds > 0 && scalar @{$rounds[$#rounds]->{'parallels'}}) == 1) {
	$finishing_valid = 1;
}

# If there have been no rounds, check out the number of participants; if not, check the
# number of qualified from the last round
my $num_qualified;
if ($num_rounds == 0) {
	my $ref = $dbh->selectrow_hashref('SELECT COUNT(*) AS num_participants FROM tournamentparticipation WHERE tournament=?', undef, $id);
	$num_qualified = $ref->{'num_participants'};
} else {
	my $ref = $dbh->selectrow_hashref('SELECT SUM(numqualifying) AS numqualifying FROM rounds NATURAL JOIN groups WHERE tournament=? AND round=?', undef, $id, $num_rounds);
	$num_qualified = $ref->{'numqualifying'};
}

# And last: If there is a ranking list, the tournament is closed and we really can't
# do anything more
if ($num_rankings > 0) {
	$closing_valid = 0;
	$finishing_valid = 0;
	if ($#rounds > -1) {
		$rounds[$#rounds]->{'locked'} = 1;
	}
}

ccbs::print_header();
ccbs::process_template('show-tournament.tmpl', $tournament->{'tournamentname'}, {
	tournament => $tournament,
	rankings => $rankings,
	num_rankings => $num_rankings,
	rounds => \@rounds,
	num_rounds => $num_rounds,
	num_qualified => $num_qualified,
	songs => $songs,
	closing_valid => $closing_valid,
	finishing_valid => $finishing_valid,
	bigscreen => $bigscreen
});
$dbh->disconnect;
