# Arch Perl library, Copyright (C) 2004 Mikhael Goikhman, Enno Cramer
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

use 5.006;
use strict;
use warnings;

package ArchWay::Widget::Inventory::Tree;

use Glib qw(TRUE FALSE);

use Arch::Inventory qw(:type);

use base qw(ArchWay::Widget::Tree);

use constant MODEL_COL_TYPES => qw(
		Glib::String

		Glib::Scalar
);

use constant MODEL_COL_NAME  => 0;
use constant MODEL_COL_ENTRY => 1;

sub new ($$) {
	my $class     = shift;
	my $inventory = shift;

	my $self = $class->SUPER::new(Gtk2::TreeStore->new(MODEL_COL_TYPES));
	$self->add_columns(
		{
			title  => 'Filename',
			renderer =>	{
				class   => 'Gtk2::CellRendererText',
				static  => {},
				dynamic => { text => MODEL_COL_NAME },
			},
			sort_column => MODEL_COL_NAME,
		},
	);

	$self->show($inventory) if ($inventory);

	return $self;
}

sub get_selected_path ($) {
	my $self = shift;

	return $self->get_selection->count_selected_rows
		? $self->get_selected(MODEL_COL_ENTRY)->{path}
		: undef;
}

sub get_selected_parent_path ($) {
	my $self = shift;

	my $model = $self->get_model;
	my $path = ($self->get_selection->get_selected_rows)[0];

	if ($path && ($path->get_depth > 1)) {
		$path->up;
		return $model->get($model->get_iter($path), MODEL_COL_ENTRY)->{path};
	} else {
		return undef;
	}
}

sub select_by_path ($$) {
	my $self = shift;
	my $path = shift;

	$self->select(sub { $_[0]->get($_[1], MODEL_COL_ENTRY)->{path} eq $path });
}

sub show ($$) {
	my $self      = shift;
	my $inventory = shift;

	my $model = $self->get_model;
	$model->clear;

	return unless (defined $inventory);

	my $top = $model->append(undef);
	$model->set($top,
		MODEL_COL_NAME, '/',
		MODEL_COL_ENTRY, $inventory,
	);

	tree_model_append($model, $top, $inventory);

	$self->get_selection->select_iter($top);
	$self->expand_row(Gtk2::TreePath->new_from_indices(0), FALSE);
}

sub tree_model_append ($$$) {
	my ($model, $parent, $entry) = @_;

	foreach my $name (sort keys %{$entry->{children}}) {
		my $child = $entry->{children}->{$name};

		next unless ($child->{type} eq DIRECTORY);

		my $iter = $model->append($parent);
		$model->set($iter,
			MODEL_COL_NAME, $name,
			MODEL_COL_ENTRY, $child,
		);

		&tree_model_append($model, $iter, $child);
	}
}

1;

__END__
