package Lire::UI::SelectWidget;

use strict;

use base qw/ Curses::UI::Popupmenu Lire::UI::Widget /;

use Curses::UI::Common;

use Lire::Utils qw/ item_index check_object_param /;
use Locale::TextDomain 'lire';

use Carp;
use vars qw/@CARP_NOT/;

@CARP_NOT = qw/Curses::UI::Container/;

sub new {
    my $class = shift;
    my %userargs = @_;
    keys_to_lowercase(\%userargs);

    check_object_param( $userargs{'value'}, 'value',
                        'Lire::Config::Scalar' );

    my @options = map { $_->name() } $userargs{'value'}->spec()->options();
    my $selected;
    my $focusable;

    if (@options) {
        $selected = ( $userargs{'value'}->is_valid()
                      ? item_index( \@options, $userargs{'value'}->get() )
                      : undef );
        $focusable = 1;
    } else {
        @options = ( __( '-- empty list --' ) );
        $selected = 0;
        $focusable = 0;
    }

    my %args = ( %userargs,
                '-height' => 1,
                 '-onchange' => \&_on_change_cb,
                 '-selected' => $selected,
                 '-values' => \@options,
                 '-focusable' => $focusable );

    return $class->Curses::UI::Popupmenu::new( %args );
}

sub layout {
    my $self = $_[0];

    $self->{'-height'} = 1;
    return $self->SUPER::layout();
}

# callbacks
sub _on_change_cb {
    my $self = $_[0];

    $self->{'value'}->set( $self->get() );
    $self->run_event( 'onvaluechanged' );

    return;
}

1;
