package Lire::UI::XMLSpecListWidget;

use strict;

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

use Curses::UI::Common qw/keys_to_lowercase/;
use Lire::ReportSpec;
use Lire::Config::XMLSpecListSpec;
use Lire::Utils qw/check_object_param/;
use Carp;

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

    my $value = $userargs{'value'};
    check_object_param( $value, 'value', 'Lire::Config::List' );
    croak "'value' parameter's spec should be a 'Lire::Config::XMLSpecListSpec' instance, not '", $value->spec(), "'"
      unless $value->spec()->isa( 'Lire::Config::XMLSpecListSpec' );

    my $self = $class->SUPER::new( %userargs );

    $self->set_routine( 'edit-element', \&edit_element );
    return $self;
}

sub superservice_filter {
    my ( $self, $superservice ) = @_;

    if ( @_ == 2 ) {
        $self->{'superservice'} = $superservice;
        $self->update_type_popupmenu();
        $self->getobj( 'type_widget' )->draw(1);
    }
    return $self->{'superservice'};
}

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

    my $popup = $self->getobj( 'type_widget' );
    if ( $self->{'superservice'} ) {
        my $rx = qr/^$self->{'superservice'}:(.*)/;
        my @values = ();
        foreach my $spec_id ( $self->{'value'}->spec()->component_names() ) {
            my ($type) = $spec_id =~ /$rx/;
            next unless $type;
            push @values, $type;
        }
        $popup->{'-values'} = [ sort @values ];
    } else {
        $popup->{'-values'} = [];
    }
    $popup->{'-labels'} = {};

    return;
}

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

    return undef unless $self->{'superservice'};
    my $type = $self->getobj( 'type_widget' )->get();
    return undef unless defined $type;

    return $self->{'value'}->spec()->get( "$self->{'superservice'}:$type" )->instance();
}

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

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

    my $info;
    if ( $self->{'value'}->spec()->type() eq 'reports' ) {
        my ( $super, $type ) =
          $list_widget->get()->name() =~ /$Lire::Config::XMLSpecListSpec::NAME_RE/;
        $info = Lire::ReportSpec->load( $super, $type )->create_table_info();
        $info->set_variables_indices();
    }
    $self->SUPER::edit_element();

    $info->reset_variables_indices() if $info;

    return;
}

1;
