package Lire::UI::CompoundListWidget;

use strict;

use base qw/ Lire::UI::ListWidget /;

use Curses;
use Curses::UI::Common;
use Locale::TextDomain 'lire';

sub new {
    my $class = shift;
    my $self = $class->SUPER::new( @_ );

    $self->set_routine( 'edit-element', \&edit_element );
    $self->getobj( 'list' )->set_binding( sub { $self->do_routine( 'edit-element' ) },
                                          KEY_ENTER() );

    return $self;
}

# List API
sub add_buttons_widget {
    my $self = $_[0];

    $self->SUPER::add_buttons_widget();
    my $buttons = $self->getobj( 'buttons' );
    splice @{$buttons->{'-buttons'}}, 1, 0,
    { '-label' => __( 'Edit' ),
      '-onpress' => sub { $self->do_routine( 'edit-element' ) } };

    return;
}

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

    $self->getobj( 'buttons' )->{'-buttons'}[1]{'-label'} = __( 'Edit' );
    $self->SUPER::layout_buttons();

    return;
}

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

    my $new_instance = $self->{'component'}->instance();
    return $new_instance 
      if $self->root()->userdata()->edit_value_dialog( $new_instance );

    return undef;
}

# Routines
sub edit_element {
    my $self = $_[0];
    my $list_widget = $self->getobj( 'list' );

    return unless $list_widget->{'-focusable'};

    my $instance = $list_widget->get();
    my $new_instance = $instance->clone();
    if ( $self->root()->userdata()->edit_value_dialog( $new_instance ) ) {
        $self->{'value'}->set( $list_widget->{'-selected'}, $new_instance );
        $self->refresh_view();
        $self->run_event( 'onvaluechanged' );
    }

    return;
}

1;
