package PS::MOPS::DC::Test::Instance::Database::Table;

## @class PS::MOPS::DC::Test::Instance::Database::Table
#
# @par DESCRIPTION
# Representation of a database table.
#
# @par ATTRIBUTES
#
# _NAME
# _FIELD_NAMES_TYPES
# _DB - Database object linked to the Test Instance.

use strict;
use warnings;
our $VERSION = sprintf "%d", q$Revision: $ =~ /(\d+)/g;

sub new;
sub DESTROY;
my $_init=sub{};
my $_fillFieldNamesTypes=sub{};
sub getFieldNamesTypes;
sub identify;
sub isEmpty;

# Constructor.
#
# name
# db
sub new
{
    my ($class,%arg)=@_;
    my $self={};
    $self->{_NAME}=$arg{name};
    $self->{_DB}=$arg{db};
    $self->{_FIELD_NAMES_TYPES}=undef;
    bless($self, $class);
    $self->$_init();
    return $self;
}

sub identify
{
    print "PS::MOPS::DC::Test::Instance::Database::Table\n";
}

# Destructor.
sub DESTROY
{
}

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

    # Get the field names and types from the database table.
    $self->$_fillFieldNamesTypes();
};

# Return field names and types as a reference to an array of hashes.
sub getFieldNamesTypes
{
    my ($self)=shift;
    return $self->{_FIELD_NAMES_TYPES};
}

# Return reference to an array of hashes containing field names and types for
# a database table. The hashes have keys:
#
# name, type
$_fillFieldNamesTypes=sub
{
    my ($self)=shift;

    # Given a table name, retrieve the field names and data types for that
    # table.
    my $sql="SHOW fields FROM $self->{_NAME}";
    my $dbh=$self->{_DB}->getHandle();
    my $sth=$dbh->prepare($sql);
    $sth->execute();
    my @name_type=();
    my $cnt=0;

    while ( my $q = $sth->fetchrow_arrayref ) {
        foreach my $value (@$q) {
            $name_type[$cnt]->{name}=@$q[0];
            $name_type[$cnt]->{type}=@$q[1];
        }
        $cnt++;
    }
    $self->{_FIELD_NAMES_TYPES}=\@name_type;
};

# Return 1 if the table is empty.
sub isEmpty
{
    my ($self)=shift;
    my $sql="SELECT * FROM $self->{_NAME}";
    my $dbh=$self->{_DB}->getHandle();
    my $sth=$dbh->prepare($sql);
    $sth->execute();
    my $cnt=0;
    while ( my $q = $sth->fetchrow_arrayref ) {
        $cnt++;
    }
    my $empty=$cnt==0;
    return $empty;
}

1;
