#! /usr/bin/perl

use ccbs;
use strict;
use warnings;

ccbs::admin_only();

my $dbh = ccbs::db_connect();
my $cgi = new CGI;

$dbh->{AutoCommit} = 0;

my $tournament = $cgi->param('tournament');
my %already_ordered = ();
my $ranking = 1;
my $points = 100;

# Grab all the groups; we order by the simple criteria:
# 1. If player A has gone to group X and player B hasn't, player A is higher.
# 2. If player A has a higher (max sum of songs)/(max feet of songs) (where
#    any chosen song counts for 10) than B, player A is higher.
my $scores = ccbs::db_fetch_all($dbh, 'SELECT player FROM scores NATURAL JOIN tournaments NATURAL JOIN max_single_feetrating WHERE tournament=? GROUP BY round,player ORDER BY round DESC,SUM(score)/SUM(CASE WHEN chosen THEN 10 ELSE feetrating END) DESC',
	$tournament);
for my $s (@$scores) {
	next if ($already_ordered{$s->{'player'}});
	$dbh->do('INSERT INTO tournamentrankings (tournament, ranking, player, points) VALUES (?,?,?,?)',
			undef, $tournament, $ranking, $s->{'player'}, points_for_place($ranking));
	$ranking++;
	$already_ordered{$s->{'player'}} = 1;
}

$dbh->commit;
$dbh->disconnect;

ccbs::print_see_other('show-tournament.pl?id=' . $tournament);

# gives the usual 100, 90, 81, 73, 60, 55, ... series
sub points_for_place {
	my $n = shift;
	if ($n <= 10) {
		return 111 - (23/2) * $n + (1/2) * $n * $n;
	} elsif ($n <= 56) {
		return 56 - $n;
	} else {
		return 0;
	}
}
