package Locale::PO::Wrapper;
use Modern::Perl '2012';
use experimental 'switch';
use Carp;

use Locale::PO;
use Set::Tiny 'set';

use Moo;
use namespace::clean;

# This is a horrible idea.
# Really, it's very bad.
# We need Locale::PO to have a way to return de-quoted strings.
# Until then, we have this.

# The PO that we will be wrapping
has 'po' => (
	is => 'ro',
	required => 1,
);

# the list of functions that need to have dequote applied to them
my $dequote_functions = set(qw[fuzzy_msgctxt fuzzy_msgid fuzzy_msgid_plural msgctxt msgid msgid_plural msgstr]);

# the AUTOLOAD function will pass any calls on to the PO, except for the msgstr_n function we've defined below
# any function in the set above will have dequote called on the return value
sub AUTOLOAD {
	my $func = our $AUTOLOAD;
	$func =~ s/.*:://; # strip the package name
	my $self = shift;
	my $po = $self->po;
	if ($dequote_functions->member($func)) {
		return Locale::PO->dequote($po->$func(@_));
	}
	else {
		return $po->$func(@_);
	}
}

# we have to iterate through the structure to dequote the keys here, so we can't use
# the autoload stuff above.
sub msgstr_n {
	my $self = shift;
	if (@_) { $self->po->msgstr_n(@_); }
	else {
		my $ret = $self->po->msgstr_n;
		foreach my $key (keys %$ret) {
			$ret->{$key} = Locale::PO->dequote($ret->{$key});
		}
		return $ret;
	}
}

1;