#!/usr/bin/perl

# (C) Daniel Kasak: dan@entropy.homelinux.org
# See COPYRIGHT file for full license

package Gtk2::Ex::Datasheet::DBI;

use strict;
use warnings;

use DBI;

use Glib qw/TRUE FALSE/;

use Gtk2::Ex::Dialogs (
			destroy_with_parent	=> TRUE,
			modal			=> TRUE,
			no_separator		=> FALSE
		      );

use Gtk2::Ex::Simple::List;

BEGIN {
	$Gtk2::Ex::DBI::Datasheet::VERSION = '0.1';
}

sub new {
	
	my ( $class, $req ) = @_;
	
	# Assemble object from request
	my $self = {
			dbh		=> $$req{dbh},		# A database handle
			table		=> $$req{table},	# The source table
			primarykey	=> $$req{primarykey},	# The primary key ( needed for inserts / updates )
			sql_select	=> $$req{sql_select},	# The 'select' clause of the query
			sql_where	=> $$req{sql_where},	# The 'where' clause of the query
			sql_order_by	=> $$req{sql_order_by},	# The 'order by' clause of the query
			treeview	=> $$req{treeview},	# The Gtk2::Treeview to construct a SimpleList from
			status_label	=> $$req{status_label},	# A Gtk2::Label to print our status to
			fields		=> $$req{fields},	# Field definitions
			defaults	=> $$req{defaults},	# Default values ( HOH )
			changelock	=> 0			# Prevents the 'changed' flag from being set when we're moving records
	};
	
	bless $self, $class;
	
	if ($self->{treeview}) {
		$self->create_simplelist;
	}
	
	$self->query;
	
	return $self;
	
}

sub create_simplelist {
	
	my $self = shift;
	
	# Assemble array of fields
	my @slist_definition;
	push @slist_definition, $self->{treeview};
	
	for my $field (@{$self->{fields}}) {
		push @slist_definition, $field->{display}, $field->{renderer} || "text";
	}
	
	# Set up simplelist
	$self->{simplelist} = Gtk2::Ex::Simple::List->new_from_treeview(@slist_definition);
	
	# Enable editing for all columns and set up CellRendererCombos
	for my $counter ( 0 .. (scalar(@{$self->{fields}}) - 1) ) {
		$self->{simplelist}->set_column_editable($counter,1);
		if ($self->{fields}[$counter]->{model}) {
			my $combo = ($self->{simplelist}->get_column($counter)->get_cell_renderers)[0];
			$combo->set (
					model		=> $self->{fields}[$counter]->{model},
					text_column	=> 1
				    );
		}
	}
	
	$self->{simplelist}->get_model->signal_connect( "row-changed" => sub { $self->changed(@_) } );
	
}
	
sub query {
	
	my ( $self, $sql_where ) = @_;
	
	if (defined $sql_where) {
		$self->{sql_where} = $sql_where;
	}
	
	$self->{fetched_data} = $self->{dbh}->selectall_arrayref(
		$self->{sql_select}
		. " from " . $self->{table}
		. " " . $self->{sql_where}
	);
	
	$self->{changelock} = 1;
	$self->{simplelist}->set_data_array($self->{fetched_data});
	$self->{changelock} = 0;
	
}

sub changed {
	
	my ( $self, $liststore, $treepath, $treeiter ) = @_;
	
	if (!$self->{changelock}) {
		$self->{changed} = 1;
		$self->{status_label}->set_markup("<span color='red'><b>Changed</b></span>");
	}
	
}


1;