package lang_select;

use strict;
use base 'Exporter';

use vars qw($VERSION @EXPORT);

@EXPORT = qw/makeParams preferredLanguage locationLanguage/;
$VERSION = '0.1';


sub makeParams {
	my ($env) = @_;

	my ($name, $params, $query);

	($name, $query) = ($env->{'QUERY_STRING'}) ? ('', $env->{'QUERY_STRING'}) :
						( split(/\?/, $env->{'HTTP_REFERER'} || '') );
	if (defined $env->{'HTTP_REFERER'}) {
		($name, $params) = split(/\?/, $env->{'HTTP_REFERER'});
	}
	return (defined $params) ? join('&', $params, $query) : $query;
}


sub preferredLanguage {
	my ($lang_string, $clist) = @_;
	$clist ||= [];

	my @languages = split(/,/, $lang_string || 'en-us');

	my %priorities = map { reverse split(/;/, ($_ =~ /;/) ? $_ : "$_;q=1" ) } @languages;

	my %sorted;

	foreach my $code (keys %priorities) {
		my ($q, $val) = split(/=/, $code);
		$sorted{$val} = $priorities{$code};
	}

	my $ordered = [ map { $sorted{$_} } reverse sort keys %sorted ];

	my $regex = join('|', @$clist);
	my $filtered  = [ grep /^($regex)/, @$ordered ];
	return shift @$filtered;
}


sub locationLanguage {
	my ($IP, $clist) = @_;

	$clist ||= [];
	$IP ||= '';

	my $reg = IP::Country::Fast->new();

 	my $country = ($IP) ? $reg->inet_atocc($IP) : '';

	my $regex = join('|', @$clist);

	return ($country && $country =~ /^($regex)/i ) ? lc $country : '';
}


1;

__END__