package Locale::Babelfish::Simple;

# ABSTRACT: Babelfish parse/compile single tepmlate only.

our $VERSION = '2.003'; # VERSION

use utf8;
use strict;
use warnings;

use Exporter qw( import );
use Locale::Babelfish::Phrase::Pluralizer ();
use Locale::Babelfish::Phrase::Parser     ();
use Locale::Babelfish::Phrase::Compiler   ();

our @EXPORT_OK = qw( &single_template &t_or_undef );


sub phrase_need_compilation {
    my ($phrase) = @_;
    die "L10N: $phrase is undef" unless defined $phrase;
    return
         1
      && ref($phrase) eq ''
      && $phrase =~ m/ (?: \(\( | \#\{ | \\\\ )/x;
}


sub single_template {
    my ( $sentence, $locale ) = @_;

    my $parser = Locale::Babelfish::Phrase::Parser->new( $sentence, $locale );
    my $compiler = Locale::Babelfish::Phrase::Compiler->new();

    $sentence = $compiler->compile( $parser->parse )
      if phrase_need_compilation($sentence);
}


sub t_or_undef {
    my ( $single_template, $params, $locale ) = @_;

    if ( ref($single_template) eq 'CODE' ) {
        my $flat_params = {};

        # Convert parameters hash to flat form like "key.subkey"
        if ( defined($params) ) {

            # Scalar interpreted as { count => $scalar, value => $scalar }.
            if ( ref($params) eq '' ) {
                $flat_params = {
                    count => $params,
                    value => $params,
                };
            }
            else {
                _flat_hash_keys( $params, '', $flat_params );
            }
        }

        return $single_template->($flat_params);
    }
    return $single_template;
}


sub _flat_hash_keys {
    my ( $hash, $prefix, $store ) = @_;
    while ( my ( $key, $value ) = each(%$hash) ) {
        if ( ref($value) eq 'HASH' ) {
            _flat_hash_keys( $value, "$prefix$key.", $store );
        }
        else {
            $store->{"$prefix$key"} = $value;
        }
    }
    return 1;
}

__END__

=pod

=encoding UTF-8

=head1 NAME

Locale::Babelfish::Simple - Babelfish parse/compile single tepmlate only.

=head1 VERSION

version 2.003

=head1 METHODS

=head2 single_template

Generates template.

=head2 t_or_undef

Get internationalized value for single_template.

    t_or_undef( single_template );
    t_or_undef( single_template, { param1 => 1 , param2 => { next_level  => 'test' } } );
    t_or_undef( single_template, { param1 => 1 }, $specific_locale );
    t_or_undef( single_template, 1 );

=for Pod::Coverage phrase_need_compilation

=for Pod::Coverage _flat_hash_keys

=head1 AUTHORS

=over 4

=item *

Akzhan Abdulin <akzhan@cpan.org>

=item *

Igor Mironov <grif@cpan.org>

=item *

Victor Efimov <efimov@reg.ru>

=item *

REG.RU LLC

=back

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2014 by REG.RU LLC.

This is free software, licensed under:

  The MIT (X11) License

=cut
