#! /usr/bin/perl

use ccbs;
use strict;
use warnings;

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

my $tournament = $cgi->param('tournament');
my $round = $cgi->param('round');
my $group = $cgi->param('group');

$dbh->{AutoCommit} = 0;

# Loop through all parameters and see what parameters differ between old- and current
# versions
for my $p ($cgi->param()) {
	next if ($p =~ /^old-(.*?)$/);
	next unless (defined($cgi->param('old-' . $p)));
	next if ($cgi->param($p) eq $cgi->param('old-' . $p));

	my $val = $cgi->param($p);
	undef $val if ($val =~ /^\s*$/);

	if ($p =~ /^score(\d+)-(\d+)/) {
		$dbh->do('UPDATE scores SET score=? WHERE tournament=? AND round=? AND parallel=? AND player=? AND songnumber=?', undef,
			$val, $tournament, $round, $group, $1, $2);
	} elsif ($p =~ /^playmode(\d+)-(\d+)/) {
		$dbh->do('UPDATE scores SET playmode=? WHERE tournament=? AND round=? AND parallel=? AND player=? AND songnumber=?', undef,
			$val, $tournament, $round, $group, $1, $2);
	} elsif ($p =~ /^difficulty(\d+)-(\d+)/) {
		$dbh->do('UPDATE scores SET difficulty=? WHERE tournament=? AND round=? AND parallel=? AND player=? AND songnumber=?', undef,
			$val, $tournament, $round, $group, $1, $2);
	}
}

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

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

