#!/usr/bin/env perl
# MiF. 2006. alexey@mitme.ru
# Localization framework ;-)
package localization::localization;
use Carp qw(carp);

our %loc;

sub import
{
	my $class = shift;
	my $lang = $ENV{'LANG'};
	unless ($lang)
	{
		$lang = 'en';
		carp "Fallback to localization: en\n";
	}
	$lang = 'en' if ($lang =~ /^English$/i);
	$lang = 'ru' if ($lang =~ /^Russian$/i);

	my $path = __FILE__;
	$path =~ s/\/[^\/]*$//gos;
	my $content = `cat $path/$lang 2>/dev/null`;
	carp "Localization file '$path/$lang' not found.\nFallback to default localization\n" unless ($content);
	foreach my $from (split (/\n/,$content))
	{
		$from =~ s/\s+$//gos;
		next unless ($from);
		if ($from =~ /^\s*(["'])(.*?[^\\])\1\s*=\s*\1(.*?[^\\])\1\s*;\s*$/os)
		{
			my ($str1,$str2) = ($2,$3);
			$loc{$str1} = $str2;
		}
		else
		{
			carp "Bad localization line:\n$from\n";
		}
	}
	my $caller = caller(0);
	*{$caller."::_L"} = \&translate; 
}

sub locEscape
{
	return unless $_[0];
	$_[0] =~ s/\\/\\\\/gos;
	$_[0] =~ s/\t/\\t/gos;
	$_[0] =~ s/\r/\\r/gos;
	$_[0] =~ s/\n/\\n/gos;
	$_[0] =~ s/\$/\\\$/gos;
	return $_[0];
}

sub locUnescape
{
	return unless $_[0];
	$_[0] =~ s/\\t/\t/gos;
	$_[0] =~ s/\\r/\r/gos;
	$_[0] =~ s/\\n/\n/gos;
	$_[0] =~ s/\\\$/\$/gos;
	$_[0] =~ s/\\\\/\\/gos;
	return $_[0];
}

sub translate
{
	my $phrase = shift;
	my $keyphrase = $phrase;
	locEscape($keyphrase);
	my $res =  $loc{$keyphrase};
	if ($res)
	{
		locUnescape($res);
	}
	else
	{
		$res = $phrase;
	}
	foreach my $arg (@_)
	{
		$res =~ s/%#/$arg/s;
	}
	return $res;
}

1;
