package Lire::UI::ScalarListWidget;

use strict;

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

use Locale::TextDomain 'lire';
use Carp;

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

    $self->getobj( 'list' )->onChange( \&_value_change_cb );
    $self->set_routine( 'apply-changes', \&apply_changes );

    return $self;
}

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

    my $selected = $self->getobj( 'list' )->{'-selected'};
    my $value = ( defined $selected
                  ? $self->{'value'}->get( $selected )->clone()
                  : $self->{'component'}->instance() );

    $self->add( 'value_widget', 'Lire::UI::Widget',
                'value' => $value );

    $self->SUPER::add_contained_widgets();

    return;
}

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

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

    return;
}

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

    # Scalar widget have an invariant height;
    return $self->getobj( 'value_widget' )->{'-height'};
}

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

    my $value = $self->getobj( 'value_widget' );
    return $self unless $value;

    $value->{'-width'} = $self->canvaswidth() - 2;
    $value->{'-x'} = 1;
    $value->{'-y'} = $self->canvasheight() - (1 + $value->{'-height'});

    return $self->SUPER::layout_contained_objects();
}

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

    $self->getobj( 'buttons' )->{'-buttons'}[1]{'-label'} = __( 'Apply' );

    $self->SUPER::layout_buttons();

    return;
}

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

    my $value = $self->getobj( 'value_widget' )->{'value'};
    return $self->{'component'}->instance( 'value' => $value->get() );
}

# Routines
sub apply_changes {
    my $self = $_[0];

    my $list_widget = $self->getobj( 'list' );
    my $value_widget = $self->getobj( 'value_widget' );
    return unless defined $list_widget->{'-selected'};

    my $value = $self->{'value'}->get( $list_widget->{'-selected'} );
    $value->set( $value_widget->{'value'}->get() );

    $self->refresh_view();
    $self->run_event( 'onvaluechanged' );

    return;
}

# Event handlers
sub _value_change_cb {
    my $list_widget = $_[0];

    croak "'-selected' can never be undefined"
      unless defined $list_widget->{'-selected'};

    my $self = $list_widget->parent();
    return unless ( $self->{'component'}->isa('Lire::Config::ScalarSpec') );

    my $new_value = $self->{'value'}->get( $list_widget->{'-selected'} );
    my $value_widget = $list_widget->parent()->getobj( 'value_widget' );
    $value_widget->{'value'}->set( $new_value->get() );
    $value_widget->refresh_view();

    return;
}


1;
