%%START_PERL%%

use Carp;
use strict;

%%GENEX_EXTRALIBS%%
use CGI qw/:standard :html3 :Carp/; # LS's CGI thingie
use CGI::Carp qw(fatalsToBrowser);
use DBI;              # and the DBI module
use Bio::Genex;

my $cgi_bin = '%%GENEX_URL_EXAMPLE%%';

# ======= Start composing HTML page =====
my $q = new CGI;
print $q->header(), $q->start_html(-title => 'GeneX Database Query Form');

# ===============  Get the params from the Web Page via CGI  ==============
my $DEBUG = 0;

if (param) {
  $DEBUG = param('DEBUG') if defined param('DEBUG');
  $Bio::Genex::DBNAME = param('dbname') if defined param('dbname');
}

my @sources;
my $dbh;
if ($Bio::Genex::DBMS eq 'Pg') {
# there is a bug in DBD::Pg 0.95 that prevents data_sources from 
# working, so we do it by hand
  require DBD::Pg;
  my $connect_string  = 'dbi:Pg:dbname=template1';
  my ($sth);
  $dbh =  DBI->connect($connect_string,
		       $Bio::Genex::RO_USERNAME,
		       $Bio::Genex::RO_PASSWORD);

  $sth = $dbh->prepare("SELECT datname FROM pg_database ORDER BY datname");
  if (defined $sth) {
    $sth->execute;
    my (@datname);
    while (@datname = $sth->fetchrow_array) {
      push @sources, "$datname[0]";
    }
  }
  $sth->finish;
  $dbh->disconnect();
} else {
  $ENV{DBI_USER} = $Bio::Genex::RO_USERNAME;
  $ENV{DBI_PASS} = $Bio::Genex::RO_PASSWORD;
  @sources = DBI->data_sources($Bio::Genex::DBMS);

  # strip the sources to be readable
  @sources = map {s/[^=]+=//;} @sources
} 

# start a connection to genex
$dbh = Bio::Genex::current_connection();

# ==========  Got all params, now do something useful with them ============

#
# Grab the list of all DB tables
#
my $sth = $dbh->table_info || die $DBI::errstr;
my @tables;
while (my ($name,$type) = ($sth->fetchrow_array)[2..3]) {
  die $DBI::errstr if $sth->err;

  # we only want tables
  next unless $type eq 'TABLE';

  # skip postgres system tables
  next if $name =~ /^pga_/;

  push(@tables,$name);
}

if ($DEBUG) {
  print $q->table({-border => ''},
		  caption('Values of CGI parameters'),
		  Tr([th(['parameter name','parameter value']),
		      td(['DEBUG', $DEBUG]),
		     ])
		 );
}

#
# Make the output
#
unless (scalar @tables >  0) {
  print $q->h1("Error: couldn't find any tables");
  print $q->end_html;
}

print  $q->h1({-align=>'CENTER'},"Tables in GeneX on host: $Bio::Genex::HOST, in DB: $Bio::Genex::DBNAME");

print $q->start_multipart_form(-action=>"$cgi_bin/fetch_table.pl", 
			   -method=>'POST');

if ($DEBUG) {
  print $q->p("If you want to query a DB other than $Bio::Genex::DBNAME, then choose it from this list");

  print $q->scrolling_list(-name =>'dbname',
			   -multiple=>0, 
			   -size=> 12,
			   -default=>$Bio::Genex::DBNAME,
			   -value=>\@sources,
			  );
}

print $q->p('Choose a table to investigate, and hit the \'Retrieve Data\' button, to see all rows in that table (current limit is 100 rows)');

print $q->radio_group(-name =>'table',
		       -cols=> 4,
		       -value=>\@tables,
		      );
print $q->table({-cols=>3,
	     -align=>'CENTER',
	    },
	    $q->Tr([$q->td([$q->submit(-name=>"FETCH",
			   -value=>'Retrieve Data')]),
	       ])
	   );
print $q->hidden({-name=>'DEBUG',-value=>$DEBUG});
print $q->hidden({-name=>'dbname',-value=>$Bio::Genex::DBNAME});
print $q->end_form;
print $q->end_html;
