############################################################################
##      Copyright (C) 2006 Subredu Manuel  <diablo@iasi.roedu.net>.        #
##                                                                         #
## This program is free software; you can redistribute it and/or modify    #
## it under the terms of the GNU General Public License v2 as published by #
## the Free Software Foundation.                                           #
##                                                                         #
## 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.                                                      #
############################################################################

package RoPkg::DBCollection;

use strict;
use warnings;

use SQL::Abstract;
use DBI;
use Scalar::Util qw(blessed);

use vars qw($VERSION $dbo_method);

use RoPkg::DB;
use RoPkg::Exceptions;
use RoPkg::Utils qw(CheckParam);

$VERSION='0.1.3';

sub new {
  my ($class, %opt) = @_;
  my $self;

  CheckParam(\%opt,qw(dbo dbo_method));
  $dbo_method = $opt{dbo_method};

  $self = bless { %opt }, $class;
  
  $self->{sa}    = SQL::Abstract->new();
  $self->{table} = '_table_name_has_not_been_set_';

  return $self;
}

# Returns the database handle of the database connection
sub dbh {
  my ($self) = @_;

  if (!blessed($self)) {
    OutsideClass->throw(
      error    => 'Called outside class instance',
      pkg_name => 'RoPkg::DBCollection'
    );
  }

  return $self->{dbo}->$dbo_method();
}

sub dbo {
  my ($self) = @_;

  if (!blessed($self)) {
    OutsideClass->throw(
      error    => 'Called outside class instance',
      pkg_name => 'RoPkg::DBCollection'
    );
  }

  return $self->{dbo};
}

sub dbo_method {
  my ($self) = @_;

  if (!blessed($self)) {
    OutsideClass->throw(
      error    => 'Called outside class instance',
      pkg_name => 'RoPkg::DBCollection'
    );
  }

  return $self->{dbo_method};
}
# Counts the number of records in a table
sub _count {
  my ($self, $fields) = @_;
  my ($sth, $sql, @bval);

  ($sql, @bval) = $self->{sa}->select($self->{table}, 'COUNT(*)', $fields);
  $sth = $self->dbh()->prepare($sql);
  $sth->execute(@bval);

  return $sth->fetchrow;
}

# Get a list of objects initialized from database
sub _get {
  my ($self, $class_name, $fields, $order_by) = @_;
  my ($sth, $sql, @bval, @result);

  if (!$class_name) {
    Param::Missing->throw(
      error    => '$class_name not specified',
      pkg_name => 'RoPkg::DBCollection',
    );
  }

  if (ref($class_name) eq 'HASH') {
    Param::Wrong->throw(
      error    => '$class_name could not be a hash reference',
      pkg_name => 'RoPkg::DBCollection',
    );
  }

  ($sql, @bval) = $self->{sa}->select($self->{table}, q{*}, $fields, $order_by);
  $sth = $self->dbh()->prepare($sql);
  $sth->execute(@bval);

  # No results ? Throw exception :)
  if ($sth->rows == 0) {
    DB::NoResults->throw(
      error    => 'No record matched your query',
      pkg_name => ref($self),
    );
  }

  # load the class
  eval "require $class_name";

  # cycle through the list of objects
  while(my $rec_hash = $sth->fetchrow_hashref) {
    my $nob;

    #create a new object
    $nob = $class_name->new(
             dbo        => $self->{dbo},
             dbo_method => $self->{dbo_method},
           );

    #initialize the object
    foreach(keys(%{ $rec_hash })) {
      my $method = $_;
      
      #only if the object have that method
      if ( $class_name->can($method) ) {
        $nob->$method( $rec_hash->{$method} );
      }
    }

    #append the object to the list
    push @result, $nob;
  }

  return @result;
}

1;

__END__


=head1 NAME

RoPkg::DBCollection - base class who can be used for collections of database objects

=head1 VERSION

0.1.3

=head1 DESCRIPTION

RoPkg::DBCollection is a class who can be used as a base class
for database collection of objects. Is used by I<RoPkg::Simba::Mirrors>
,I<RoPkg::Simba::Commands> and I<RoPkg::Simba::Excludes>. This class
should not be used directly in applications but derived.

=head1 SUBROUTINES/METHODS

=head2 new()

The class constructor. Accepts a hash with parameters. The parameters
who can be passed to new() are:

=over 3

=item dbo - database object (instance of RoPkg::DB)

=item dbo_method - database method (for use with RoPkg::DB)

=item table - the sql table name where the objects data can be found

=back

If you don't specify the B<dbo> and B<dbo_method> parameters,
a I<Param::Missing> exception is raised.

=head2 dbh()

returns the database handler (DBI object) used by the class.

=head2 _count($fields)

Returns the number of records who match the fields specified in
$fields. This method should be overriden by the child classes.
The $fields must me specified in SQL::Abstract format. Please
refer to the SQL::Abstract documentation for more details about
$fields format.

=head2 _get($class_name, $fields, $order_by)

Returns a array of initialized objects. The values are read
from the database. $class_name is the name of the class
who's gonna be instanciated. When creating the class instance
dbo and dbo_method parameters are passed to the new() method.
The records from the database must match the $fields parameter
and the order is given by $order_by. For more details of these
2 parameters please refer to SQL::Abstract documentation.
 Exceptions throwed:
 
=over 3

=item B<Param::Missing> - when $class_name has not been specified

=item B<Param::Wrong> - when $class_name is not a class name

=item B<DB::NoResults> - when the query returned 0 results

=back

=head1 SYNOPSIS

 package RoPkg::Tester;
 
 use strict;
 use warnings;
 
 use Scalar::Util qw(blessed);
 use RoPkg::Exceptions;
 use RoPkg::DBCollection;
 use vars qw(@ISA);

 @ISA=qw(RoPkg::DBCollection);

 sub new {
   my ($class, %opt) = @_;
   my $self;
 
   $self = $class->SUPER::new(%opt);
   $self->{table} = 'Mirrors';
 
   return $self;
 }
 
 sub Count {
   my ($self) = @_;
 
   if (!blessed($self)) {
     OutsideClass->throw(
       error    => 'Called outside class instance',
       pkg_name => 'RoPkg::Tester',
     );
   }
 
   return $self->_count();
 }
 
 sub Get {
   my ($self, $fields) = @_;
 
   if (!blessed($self)) {
     OutsideClass->throw(
       error    => 'Called outside class instance',
       pkg_name => 'RoPkg::Tester'
     );
   }
 
   return $self->_get('RoPkg::Simba::Mirror');
 }

 1;

 sub main {
   my ($dbc, $dbp);
 
   $dbp = new RoPkg::DB();
   $dbp->Add(
           'dbi:mysql:database=mirrors_db;host=localhost',
           'root',
           '',
           'mirrors'
         );
   
   $dbc = new RoPkg::Tester(
            dbo => $dbp,
            dbo_method => 'db_mirrors'
          );
 
   print $dbc->Count(),$/;
   
   my @mirrors = $dbc->Get();
 }
 
 main();

=head1 DIAGNOSTICS

This module comes with tests. To run them, unpack the source and use
'make test' command.

=head1 PERL CRITIC

This modules is perlcritic level 2 compliant (with 1 exception)

=head1 CONFIGURATION AND ENVIRONMENT

This module does not use any configuration files or environment variables.
However, it is possible that some dependencies to do so. Please read the
man page of each dependency to find out more information.

=head1 DEPENDENCIES

This module use the following modules:

=over 4

=item *) SQL::Abstract

=item *) DBI

=item *) Scalar::Util

=item *) RoPkg

=back

=head1 INCOMPATIBILITIES

None known to the author

=head1 BUGS AND LIMITATIONS

None known to the author

=head1 SEE ALSO

L<RoPkg::Exceptions> L<RoPkg::DB> L<RoPkg::DBObject>
L<RoPkg::Simba::Mirrors>

=head1 AUTHOR

Subredu Manuel <diablo@iasi.roedu.net>

=head1 LICENSE AND COPYRIGHT

Copyright (C) 2006 Subredu Manuel.  All Rights Reserved.
This module is free software; you can redistribute it 
and/or modify it under the same terms as Perl itself.
The LICENSE file contains the full text of the license.

=cut
