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 set_locale {
	my $locale = shift;
	$locale =~ s/-/_/;
	POSIX::setlocale(&POSIX::LC_ALL, $locale . '.UTF-8');
}

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 AND length(kultur)=5 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'} = Encode::decode_utf8($ref->{'spraak'});
		} else {
			$lang{'a'} = Encode::decode_utf8($ref->{'spraak'});
			$lang{'a/href'} = sprintf "/%s/%s", $ref->{'kultur'}, $url;
			$lang{'lang-no-link'} = '';
		}
		push @languages, \%lang;
	}

	return \@languages;
}

# mapping from locale to translation to use (if not found, "en" is used)
my %translation_mapping = (
	'nb-NO' => 'no',
	'nn-NO' => 'no',
	'da-DK' => 'no',
	'sv-SE' => 'no',
	'nl-NL' => 'en',
);

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

	my $translation = $translation_mapping{$locale} // 'en';
	my $doc;
	if (-r "../templates/$filename.$translation.xml") {
		$parms->{'html/xml:lang'} = $translation;
		$doc = XML::Template::process_file("../templates/$filename.$translation.xml", $parms);
	} else {
		$doc = XML::Template::process_file("../templates/$filename.xml", $parms);
	}
	print $doc->toString;
}

sub get_ordinal {
	my ($num, $locale) = @_;
	my $translation = $translation_mapping{$locale} // 'en';

	if ($translation eq 'no') {
		return $num . ".";
	} elsif ($translation eq 'en') {
		# http://en.wikipedia.org/wiki/English_numerals#Ordinal_numbers
		my $units = $num % 10;
		my $tens = (($num - $units) / 10) % 10;
		if ($tens == 1) {
			return $num . "th";
		} elsif ($units == 1) {
			return $num . "st";
		} elsif ($units == 2) {
			return $num . "nd";
		} elsif ($units == 3) {
			return $num . "rd";
		} else {
			return $num . "th";
		}
	} else {
		die "Missing ordinal strategy for locale $locale";
	}	
}

sub find_all_locales {
	my $dbh = shift;
	my $q = $dbh->prepare('SELECT kultur FROM fotballspraak WHERE nyestesesong <> -1 AND length(kultur)=5');
	$q->execute;

	my @locales = ();
	while (my $ref = $q->fetchrow_hashref) {
		push @locales, $ref->{'kultur'};
	}

	return @locales;
}

1;
