#! /usr/bin/perl
use strict;
use warnings;
no warnings qw(once);
use CGI;
use CGI::Carp qw( fatalsToBrowser );
use DBI;
use POSIX;
use Devel::Peek;
use HTML::Entities;
use Encode;
use locale;
require '../config.pm';

my $cgi = CGI->new;

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

my $trials = 25_000;

binmode STDOUT, ':utf8';

my %players = ();
my %ratings = ();
my @matches = ();
my %parms = ();
my $match_stddev;

sub sanitize {
	return HTML::Entities::encode_entities(shift);
}

sub color {
	my $x = shift;
	return int(255.0 * ($x ** (1.80)));
}

sub make_table {
	my $used_ratings = shift;

	print <<"EOF";

    <table>
      <tr>
        <th></th>
EOF

	POSIX::setlocale(&POSIX::LC_ALL, 'C');

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

	printf MCCALC "%f\n", $match_stddev;
	printf MCCALC "%d\n", scalar keys %players;

	for my $id (keys %players) {
		if (exists($used_ratings->{$id})) {
			printf MCCALC "%s %f\n", $id, $used_ratings->{$id};
		} else {
			printf MCCALC "%s %f\n", $id, 1500.0;
		}
	}

	for my $match (@matches) {
		printf MCCALC "%s %s %d %d\n", $match->[0], $match->[1], $match->[2], $match->[3];
	}
	close MCCALC;

	POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');

	my %prob = ();

	open MCCALC, "$config::base_dir/mcwordfeud $trials < $tmpnam |"
		or die "mccalc: $!";
	while (<MCCALC>) {
		chomp;
		my @x = split /\s+/;
		my $id = $x[0];
		my $player = $players{$id};
		$prob{$player} = [ @x[1..$#x] ];
	}
	close MCCALC;
	#unlink $tmpnam;

	my $num_games = scalar keys %prob;
	for my $i (1..$num_games) {
		print "        <th>$i.</th>\n";
	}
	print "        <th>NEDRYKK</th>\n";
	print "      </tr>\n";

	for my $player (sort { $a cmp $b } keys %prob) {
		print "      <tr>\n";
		print "        <th>$player</th>\n";

		for my $i (1..$num_games) {
			my $pn = $prob{$player}->[$i - 1] / $trials;

			my $r = color(1.0 - $pn / 3);
			my $g = color(1.0 - $pn / 3);
			my $b = color(1.0);

			if ($i == 1) {
				($g, $b) = ($b, $g);
			} elsif ($i >= $num_games - 1) {
				($r, $b) = ($b, $r);
			}

			printf "        <td style=\"background-color: rgb($r, $g, $b)\">%.1f%%</td>\n", $pn * 100.0;
		}

		{
			my $pn = ($prob{$player}->[$num_games - 1] + $prob{$player}->[$num_games - 2]) / $trials;

			my $r = color(1.0);
			my $g = color(1.0 - $pn / 3);
			my $b = color(1.0 - $pn / 3);
			printf "        <td style=\"background-color: rgb($r, $g, $b)\">%.1f%%</td>\n", $pn * 100.0;
		}
		print "      </tr>\n";
	}

	print << "EOF";
    </table>
EOF
}

# Get auxillary parameters
my $q = $dbh->prepare('SELECT * FROM ratings WHERE id < 0');
$q->execute;

while (my $ref = $q->fetchrow_hashref) {
	$parms{$ref->{'id'}} = $ref->{'rating'};
}
$match_stddev = $parms{-2} * sqrt(2.0);

my $season;
my $division = $cgi->param('divisjon') // -1;
my $subdivision = $cgi->param('avdeling') // -1;

POSIX::setlocale(&POSIX::LC_ALL, 'nb_NO.UTF-8');

print $cgi->header(-type=>'text/html; charset=utf-8', -expires=>'now');
printf <<"EOF", $match_stddev;
<html>
  <head>
    <title>WLoH-plasseringsannsynlighetsberegning</title>
    <style type="text/css">
body {
	color: black;
	background: white;
	font-family: sans-serif;
}
table {
	border-collapse: collapse;
	border: 1px solid black;
}
td, th {
	border: 1px solid black;
	padding: 5px;
}
td {
	text-align: right;
}
    </style>
  </head>
  <body>
    <h1>WLoH-plasseringsannsynlighetsberegning</h1>

    <p>Beregningen tar ikke hensyn til ujevn spillestyrke, ting som er sagt i forumet e.l.;
      den antar at samtlige uspilte kamper trekkes fra en normalfordeling med standardavvik
      %.1f poeng. Sannsynlighetene kan summere til andre tall enn 100%% pga. avrunding.
      Tallene vil variere litt fra gang til gang fordi utregningen skjer ved randomisering.</p>

    <p>Spillerne er sortert etter nick.</p>

    <form method="get" action="/">
EOF

$q = $dbh->prepare('SELECT MAX(sesong) AS max_sesong FROM fotballserier');
$q->execute;
my $season;
while (my $ref = $q->fetchrow_hashref) {
	$season = $ref->{'max_sesong'};
}

print <<"EOF";
     <p>Divisjon:
        <select name="divisjon" onchange="form.submit();">
EOF

$q = $dbh->prepare('SELECT DISTINCT(divisjon) FROM fotballserier WHERE sesong=? ORDER BY divisjon');
$q->execute($season);

my $found_division = 0;

while (my $ref = $q->fetchrow_hashref) {
	my $d = $ref->{'divisjon'};
	if ($d == $division) {
		print "        <option value=\"$d\" selected=\"selected\">$d</option>\n";
		$found_division = 1;
	} else {
		print "        <option value=\"$d\">$d</option>\n";
	}
}

$division = 1 if (!$found_division);

print <<"EOF";
        </select>
        Avdeling:
        <select name="avdeling" onchange="form.submit();">
EOF

$q = $dbh->prepare('SELECT DISTINCT(avdeling) FROM fotballserier WHERE sesong=? AND divisjon=? ORDER BY avdeling');
$q->execute($season, $division);

my $found_subdivision = 0;

while (my $ref = $q->fetchrow_hashref) {
	my $sd = $ref->{'avdeling'};
	if ($sd == $subdivision) {
		print "        <option value=\"$sd\" selected=\"selected\">$sd</option>\n";
		$found_subdivision = 1;
	} else {
		print "        <option value=\"$sd\">$sd</option>\n";
	}
}

$subdivision = 1 if (!$found_subdivision);

print <<"EOF";
        </select>
        <input type="submit" value="Vis" />
      </p>
    </form>
EOF

# Get players and ratings
$q = $dbh->prepare('SELECT fotballdeltagere.id,fotballdeltagere.navn,rating FROM fotballdeltagere JOIN fotballserier ON fotballdeltagere.serie=fotballserier.nr JOIN ratings ON fotballdeltagere.id=ratings.id AND sesong=? AND divisjon=? AND avdeling=?');
$q->execute($season, $division, $subdivision);

while (my $ref = $q->fetchrow_hashref) {
	my $id = $ref->{'id'};
	$players{$id} = sanitize(Encode::decode_utf8($ref->{'navn'}));
	$ratings{$id} = $ref->{'rating'};
}
$q->finish;

$q = $dbh->prepare('
SELECT
  d1.id AS p1, d2.id AS p2, maalfor AS score1, maalmot AS score2
FROM fotballresultater r
  JOIN fotballserier s ON r.serie=s.nr
  JOIN fotballdeltagere d1 ON r.lagrecno=d1.nr AND r.serie=d1.serie
  JOIN fotballdeltagere d2 ON r.motstander=d2.nr AND r.serie=d2.serie
WHERE
  sesong=? AND divisjon=? AND avdeling=?
  AND lagrecno > motstander
');
$q->execute($season, $division, $subdivision);

while (my $ref = $q->fetchrow_hashref) {
	push @matches, [ $ref->{'p1'}, $ref->{'p2'}, $ref->{'score1'}, $ref->{'score2'} ];
}
$q->finish;


make_table({});

print <<"EOF";
    <p>Under er en variant som pr&oslash;ver &aring; ta relativ spillestyrke med i betraktningen.
      Disse er basert p&aring; WLoH-data og oppdateres hver hele time (takk til Lobotommy for tilgang!),
      men modellen er forel&oslash;pig ikke fullstendig tunet.</p>
EOF

make_table(\%ratings);

print << "EOF";
    </table>
  </body>
</html>
EOF
