package MGH_Biostat::Locale::Locale;
use Modern::Perl '2012';
use Module::Load;

# this module implements a small subset of the what Locales.pm does.
# however, it's all we really need.
# you need to precreate the subsetted locales using the bin/make_locale.pl script
# which requires that Locales.pm be installed, and then grabs that information.
# function names are the same, so we could switch back really simply.

our @defined_keys = qw(cldr_version orientation list);

sub new {
    my $class = shift;
    my ($orig_tag) = @_;
    my $tag = ( ( $orig_tag =~ s/[^A-Za-z0-9_-]//gr ) =~ s/-/_/gr ) || 'en_US';

    my $self = {};

    my $mod = 'MGH_Biostat::Locale::DB::' . $tag;
    load $mod;

    no strict 'refs';
    foreach my $key (@defined_keys) {
        $self->{$key} = ${$mod . '::' . $key};
    }

    return bless $self, $class;
}

# return the text direction
sub get_character_orientation_from_code {
    my $self = shift;
    return $self->{'orientation'};
}

# create a list of "and"ed items
sub get_list_and {
    my $self = shift;
    my (@items) = @_;

    return '' if ( @items == 0 );
    return $items[ 0 ] if ( @items == 1 );

    if ( @items == 2 ) {
        my $two = $self->{'list'}{'2'};
        $two =~ s/\{([01])\}/$items[$1]/g;
        return $two;
    }
    else {

        my $start = $self->{'list'}{'start'};
        $start =~ s/\{([01])\}/$items[$1]/g;
        splice(@items, 0, 2, $start);

        while ( @items > 2 ) {
            my $middle = $self->{'list'}{'middle'};
            $middle =~ s/\{([01])\}/$items[$1]/g;
            splice(@items, 0, 2, $middle);
        }

        my $end = $self->{'list'}{'end'};
        $end =~ s/\{([01])\}/$items[$1]/g;

        return $end;
    }

    return '_error in list creation';
}