#! /usr/bin/perl
use DBI;
use strict;
use warnings;
no warnings qw(once);
use POSIX;
require './config.pm';

my $dbh = DBI->connect($config::local_connstr, $config::local_username, $config::local_password)
	or die "connect: " . $DBI::errstr;
$dbh->{AutoCommit} = 0;
$dbh->{RaiseError} = 1;

# Find last completely done season 
my $ref = $dbh->selectrow_hashref('SELECT sesong FROM fotballserier GROUP BY sesong HAVING COUNT(*)=COUNT(avgjort=1 OR NULL) ORDER BY sesong DESC LIMIT 1');
my $last_season = $ref->{'sesong'};

my $tmpnam = POSIX::tmpnam();
open DATA, ">", $tmpnam
	or die "$tmpnam: $!";

# Fetch name (ID) list
my $q = $dbh->prepare('SELECT DISTINCT id FROM fotballdeltagere');
$q->execute();
my @ids = ();
while (my $ref = $q->fetchrow_hashref) {
	my $id = $ref->{'id'};
	push @ids, $id;
}
	
print DATA scalar @ids, "\n";
for my $id (@ids) {
	print DATA $id, "\n";
}

# Fetch games
$q = $dbh->prepare('
SELECT
  deltager1.id as p1, deltager2.id as p2, maalfor, maalmot, least(pow(2.0, (sesong - ? + 3) / 3.0), 1.0) AS vekt
FROM
  Fotballresultater resultater
  JOIN Fotballdeltagere deltager1 ON resultater.Lagrecno=deltager1.Nr AND resultater.Serie=deltager1.Serie
  JOIN Fotballdeltagere deltager2 ON resultater.Motstander=deltager2.Nr AND resultater.Serie=deltager2.Serie
  JOIN Fotballserier serier on resultater.Serie=serier.Nr
WHERE deltager1.Nr > deltager2.nr
');
$q->execute($last_season);

while (my $ref = $q->fetchrow_hashref) {
	next if ($ref->{'maalfor'} == 150 && $ref->{'maalmot'} == 0);
	next if ($ref->{'maalfor'} == 0 && $ref->{'maalmot'} == 150);
	next if ($ref->{'maalfor'} == 150 && $ref->{'maalmot'} == 150);
	printf DATA "%d %d %d %d %f\n", $ref->{'p1'}, $ref->{'p2'}, $ref->{'maalfor'}, $ref->{'maalmot'}, $ref->{'vekt'};
}

close DATA;

$dbh->do('DELETE FROM ratings');
my $iq = $dbh->prepare('INSERT INTO ratings ( id, rating, rating_stddev ) VALUES (?, ?, ?)');

open RATINGS, "$config::base_dir/bayeswf < $tmpnam |"
	or die "bayeswf: $!";
while (<RATINGS>) {
	/(.*) (.*) (.*)/ or next;
	$iq->execute($3, $1, $2);
}

$dbh->commit;
unlink($tmpnam);
