use strict;
use warnings;
use POSIX;
use XML::Template;

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 get_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)) {
		return "(ukjent)";
	} else {
		return POSIX::strftime("%Y-%m-%d %H:%M %Z", localtime($ref->{'last_sync'}));
	}
}

sub output_last_sync {
	my $dbh = shift;
	my $ts = get_last_sync($dbh);
	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, $locale) = @_;

	my $q = $dbh->prepare('SELECT * FROM aux_params WHERE kultur=?');
	$q->execute($locale);

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

sub get_navbar {
	my ($cgi, $dbh, $locale) = @_;
	my $url = $cgi->url(-relative => 1);

	print "<p style=\"font-size: smaller;\">";

	my $q = $dbh->prepare('SELECT spraak, kultur FROM fotballspraak WHERE nyestesesong <> -1 ORDER BY id');
	$q->execute;

	my @languages = ();

	my $first = 1;
	while (my $ref = $q->fetchrow_hashref) {
		my %lang = ();
		if ($first) {
			$lang{'separator'} = '';
		}
		$first = 0;

		if ($ref->{'kultur'} eq $locale) {
			$lang{'lang-with-link'} = '';
			$lang{'lang-no-link'} = $ref->{'spraak'};
		} else {
			$lang{'a'} = $ref->{'spraak'};
			$lang{'a/href'} = sprintf "/%s/%s", $ref->{'kultur'}, $url;
			$lang{'lang-no-link'} = '';
		}
		push @languages, \%lang;
	}

	return \@languages;
}

sub print_navbar {
	my ($cgi, $dbh, $locale) = @_;
	my $url = $cgi->url(-relative => 1);

	print "<p style=\"font-size: smaller;\">";

	my $q = $dbh->prepare('SELECT spraak, kultur FROM fotballspraak WHERE nyestesesong <> -1 ORDER BY id');
	$q->execute;

	my $first = 1;
	while (my $ref = $q->fetchrow_hashref) {
		if (!$first) {
			print " :: ";
		}
		$first = 0;

		if ($ref->{'kultur'} eq $locale) {
			printf "%s ", $ref->{'spraak'};
		} else {
			printf "<a href=\"/%s/%s\">%s</a> ", $ref->{'kultur'}, $url, $ref->{'spraak'};
		}
	}
	print "</p>\n";
}

sub process_template {
	my ($filename, $parms) = @_;

	my $doc = XML::Template::process_file('../templates/' . $filename, $parms);
	print $doc->toString;
}

1;
