package ATR::Tk::CardRow;

use strict;
use warnings;


=head1 NAME

ATR::Tk::CardRow - stick a row of UpdateField widgets on a Tk::grid

=head1 DESCRIPTION

This object will create and manage a set of widgets, plus the data
object(s) backing them.

Subclasses will be for mice and litters, to cover the mating pair
card.

=cut


# $Id: CardRow.pm,v 1.5 2005/02/15 12:19:25 mca Exp $

#----------------------------------------------------------------------------


sub new {
    my $proto = shift;
    my $self = bless {}, ref($proto) || $proto;
    my @left = $self->_init(@_);
    die "Args (@left) left" if @left;
    return $self;
}

sub _init {
    my ($self, $rowName, @spare) = @_;
    # Don't stash parent info, will be circular
    $self->{_widgets} = {};
    $self->{_rowName} = $rowName;
    return @spare;
}

sub _widgets { $_[0]->{_widgets} }
sub name     { $_[0]->{_rowName} }

sub gridRow    { $_[0]->{_gridrow} }
sub setGridRow { $_[0]->{_gridrow} = $_[1] }

sub columns  {@{ $_[0]->{_cols} }}
sub setColumns {
    my $self = shift;
    $self->{_cols} = [ @_ ];
}

sub debugId {
    my $self = shift;
    my $type = ref($self);
    return "$self class" if !$type;
#    my $dataInf = $self->data ? $self->data->debugId : "new row";
    my $name = $self->name;
    my $row = $self->gridRow;
    return "$type for \$dataInf at $row #$row";
}


=head2 guiCard()

Find and return the parent L<ATR::Tk::AtrCard>, using the widget
hierarchy.

Don't call before creating at least one Tk::Widget for this object.

=cut

sub guiCard {
    my $self = shift;
    my ($widget) = values %{ $self->_widgets };
    while ($widget) {
	$widget = $widget->parent;
	return $widget if UNIVERSAL::isa($widget, 'ATR::Tk::AtrCard');
    }
    my $name = $self->name;
    die "Can't find AtrCard for $self (name=$name)";
}


=head2 show($visible)

Attach or remove the widgets using C<grid> or C<gridForget>, according
to C<$visible>.

Scans the columns configured with C<setColumns>, attaches those named
widgets in that order and hides the rest.

=cut

sub show {
    my ($self, $visible) = @_;
    my %widgets = %{ $self->_widgets };
    my $row = $self->gridRow;

    # Attach that which should be visible
    my @cols = $visible ? $self->columns : ();
    for (my $col=0; $col<@cols; $col++) {
	my $colname = $cols[$col];
	my $w = delete $widgets{$colname}; # only from our local hash
	# XXX: create on demand if !$w ?
	$w->grid(-row => $row, -column => $col, -sticky => 'nsew');
    }
    # Detach the rest
    while (my ($colname, $w) = each %widgets) {
	$w->gridForget;
    }
}

sub configAll {
    my %w = %{ (shift)->_widgets };
    my @config = @_;
    foreach my $w (values %w) {
	$w->configure(@config);
    }
}


1;
