#! /usr/bin/perl
use strict;
use warnings;
use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
require '../foosball.pm';

my $cgi = CGI->new;

my $username1 = $cgi->param('username1');
$username1 =~ /^([a-z][a-z0-9]*)$/ or die "Invalid user name 1";
$username1 = $1;

my $username2 = $cgi->param('username2');
$username2 =~ /^([a-z][a-z0-9]*)$/ or die "Invalid user name 2";
$username2 = $1;

my $score1 = $cgi->param('score1');
$score1 =~ /^([0-9]|10)$/ or die "Invalid score 1";
$score1 = $1;

my $score2 = $cgi->param('score2');
$score2 =~ /^([0-9]|10)$/ or die "Invalid score 2";
$score2 = $1;

my $dbh = foosball::db_connect();
$dbh->{AutoCommit} = 0;

foosball::create_user_if_not_exists($dbh, $username1);
foosball::create_user_if_not_exists($dbh, $username2);
$dbh->commit;

# fetch the previous single ratings
my ($rating1, $rd1) = foosball::find_single_rating($dbh, $username1);
my ($rating2, $rd2) = foosball::find_single_rating($dbh, $username2);

my $q = $foosball::q;

my ($newr1, $newrd1) = foosball::calc_rating($rating1, $rd1, $rating2, $rd2, $score1, $score2);
my ($newr2, $newrd2) = foosball::calc_rating($rating2, $rd2, $rating1, $rd1, $score2, $score1);

my $d2sq = foosball::dsq($rating2, $rating1, $rd1);
my $newr2 = $rating2 + ($q / (1.0/($rd2*$rd2) + 1.0 / $d2sq)) * foosball::g($rd1) * ($s2 - foosball::E($rating2, $rating1, $rd1));
my $newrd2 = sqrt(1.0 / (1.0 / ($rd2*$rd2) + 1.0 / $d2sq));

$dbh->do('INSERT INTO single_results (gametime,username1,username2,score1,score2) VALUES (CURRENT_TIMESTAMP,?,?,?,?)',
	undef, $username1, $username2, $score1, $score2);
$dbh->do('INSERT INTO single_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,?,?)',
	undef, $username1, $newr1, $newrd1);
$dbh->do('INSERT INTO single_rating (username,ratetime,rating,rd) VALUES (?,CURRENT_TIMESTAMP,?,?)',
	undef, $username2, $newr2, $newrd2);

$dbh->commit;

print $cgi->header(-status=>'303 See Other',
		   -location=>'http://foosball.sesse.net/');

