#!/usr/bin/perl
# BEGIN BPS TAGGED BLOCK {{{
# 
# COPYRIGHT:
#  
# This software is Copyright (c) 1996-2009 Best Practical Solutions, LLC 
#                                          <sales@bestpractical.com>
# 
# (Except where explicitly superseded by other copyright notices)
# 
# 
# LICENSE:
# 
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
# 
# This work 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., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.gnu.org/copyleft/gpl.html.
# 
# 
# CONTRIBUTION SUBMISSION POLICY:
# 
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
# 
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
# 
# END BPS TAGGED BLOCK }}}
use DBI;

my $database = shift;
my $namespace = shift;

my $CollectionBaseclass = 'RT::FM::SearchBuilder';
my $RecordBaseclass = 'RT::FM::Record';

my $driver = 'mysql';
my $hostname = 'localhost';
my $user = 'root';
my $password = '';
my $dsn = "DBI:$driver:database=$database;host=$hostname";

my $dbh = DBI->connect($dsn, $user, $password);

 
#get all tables out of database
my @tables = $dbh->tables();

my %tablemap;

foreach my $table (@tables) {
	$tablemap{$table} = $table;
}
$tablemap{'CreatedBy'} = 'User';
$tablemap{'UpdatedBy'} = 'User';



foreach my $table (@tables) {

    my $tablesingle = $table;
    $tablesingle =~ s/s$//;

    my %requirements;

    my $CollectionClassName = $namespace."::".$tablesingle."Collection";
    my $RecordClassName = $namespace."::".$tablesingle;
    
    my $path = $namespace;
    $path =~ s/::/\//g;
    
    my $RecordClassPath = $path."/".$tablesingle.".pm";
    my $CollectionClassPath = $path."/".$tablesingle."Collection.pm";


    
    #create a collection class
    my $CreateInParams;
    my $CreateOutParams;
    my $ClassAccessible = "";
    my $FieldsPod = "";
    my $CreatePod = "";
    my $sth = $dbh->prepare("DESCRIBE $table");
    $sth->execute;
    while (my $row = $sth->fetchrow_hashref()) {
		my $field = $row->{'Field'};
		my $type = $row->{'Type'};
		my $default = $row->{'Default'};
		
		#generate the 'accessible' datastructure
		$ClassAccessible .= "        $field => {'read' => 1, 'write' => 1},\n";
		
		
		#generate pod for the accessible fields
		$FieldsPod .= "
=item $field

Returns the current value of $field. 
(In the database, $field is stored as $type.)


=item Set$field VALUE

Set $field to VALUE. 
Returns (1, 'Status message') on success and (0, 'Error Message') on failure.
(In the database, $field will be stored as a $type.)

=cut

";

if ($tablemap{$field}) { 
$FieldsPod .= "
=item ${field}Obj

Returns the $tablemap{$field} Object which has the id returned by $field


=cut

sub ${field}Obj {
	my \$self = shift;
	my \$$field = new ${namespace}::$tablemap{$field}(\$self->CurrentUser);
	\$$field->Load(\$self->$field());
	return(\$$field);
}
";
$requirements{$tablemap{$field}} = "use ${namespace}::$tablemap{$field};";

}
		#generate create statement
		$CreateInParams .= "                $field => undef,\n";
                $CreateOutParams .= "                         $field => \$args{'$field'},\n";


		#gerenate pod for the create statement	
		$CreatePod .= "  $type '$field'";
		$CreatePod .= " defaults to '$default'" if ($default);
		$CreatePod .= ".\n";

	}

        $Create = "
sub Create {
    my \$self = shift;
    my \%args = ( 
$CreateInParams,
		  \@_);
    \$self->SUPER::Create(
$CreateOutParams);

}
";
	$CreatePod .= "\n=cut\n\n";


my $CollectionClass = "

# \$Header\$
# Autogenerated by DBIx::SearchBuilder factory  (by <jesse\@fsck.com>)

=head1 NAME

  $CollectionClassName -- Class Description
 
=head1 SYNOPSIS

  use $CollectionClassName

=head1 DESCRIPTION


=head1 METHODS

=cut

package $CollectionClassName;

use $CollectionBaseclass;
use $RecordClassName;

\@ISA= qw($CollectionBaseclass);


sub _Init {
    my \$self = shift;
    \$self->{'table'} = '$table';
    \$self->{'primary_key'} = 'id';
    return ( \$self->SUPER::_Init(\@_) );
}


=item NewItem

Returns an empty new $RecordClassName item

=cut

sub NewItem {
    my \$self = shift;
    return(new $RecordClassName(\@_));
}

1;
";

my $RecordClassHeader = "
# \$Header\$
# Autogenerated by DBIx::SearchBuilder factory  (by <jesse\@fsck.com>)

=head1 NAME

$RecordClassName


=head1 SYNOPSIS

=head1 DESCRIPTION

=head1 METHODS

=cut

package $RecordClassName;
use $RecordBaseclass; 
";

foreach my $key (keys %requirements) {
	$RecordClassHeader .= $requirements{$key} . "\n";
}
$RecordClassHeader .="

use vars qw( \@ISA );
\@ISA= qw( $RecordBaseclass );

sub _Init {
  my \$self = shift; 

  \$self->Table('$table');
  \$self->SUPER::_Init(\@_);
}

";








my $RecordClass = "

$RecordClassHeader

$RecordInit

=item Create PARAMHASH

Create takes a hash of values and creates a row in the database:

$CreatePod

$Create

$FieldsPod

sub _ClassAccessible {
    {
     
$ClassAccessible
 }
};
1;
";


`mkdir -p $path`;

open (RECORD, ">$RecordClassPath");
print RECORD $RecordClass;
close (RECORD);

open (COL, ">$CollectionClassPath");
print COL $CollectionClass;
close($COL);

}



	
