use strict;
use warnings;
use POSIX;

package wloh_common;

sub get_max_season {
	my ($dbh, $locale) = @_;
	my $ref = $dbh->selectrow_hashref('SELECT MAX(sesong) AS max_sesong FROM fotballserier se JOIN fotballspraak sp ON se.spraak=sp.id WHERE kultur=?',
		undef, $locale);
	return $ref->{'max_sesong'};
}

sub output_last_sync {
	my $dbh = shift;
	my $ref = $dbh->selectrow_hashref('SELECT EXTRACT(EPOCH FROM last_sync) AS last_sync FROM last_sync');
	if (!defined($ref)) {
		print "    <p class=\"lastsync\">Databasen ble sist synkronisert (ukjent).</p>\n";
	} else {
		my $ts = POSIX::strftime("%Y-%m-%d %H:%M %Z", localtime($ref->{'last_sync'}));
		print "    <p class=\"lastsync\">Databasen ble sist synkronisert $ts.</p>\n";
	}
}

sub get_locale {
	my $cgi = shift;
	my $url = $cgi->url(-absolute => 1);
	$url =~ m#^/([a-z][a-z]-[A-Z][A-Z])/# or die "Invalid locale!";
	return $1;
}

sub get_auxillary_parameters {
	my ($dbh) = @_;

	my %aux_parm_names = {
		-1 => num_iterations,
		-2 => score_stddev,
		-3 => rating_prior_stddev,
		-4 => total_log_likelihood,
	};

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

	my $aux_parms = {};
	while (my $ref = $q->fetchrow_hashref) {
		my $id = $ref->{'id'};
		$aux_parms->{$aux_parm_names{$id}} = $ref->{'rating'};
	}
	return $aux_parms;
}

1;
