#!/usr/bin/perl -w

# search_for_model.pl

# Search for models (or other words) matching your
# search list:
# 	$param{'searchstring'}

# Output is a table of database columns as defined by
# display_field_N where N=1,2,3,... (no numbers misssing)
# display_field is the database column name ordered by
# N value and the headings defined by entries in the 
# config file of the form
#	<display_field_n-value> := <column name>
# Note that you can include html tags on the right.

my $version = 'April 12, 2010/V1.00';

# April 12, 2012, V1.00 R. Groman (based on a similar
# program called search_for_species.pl.)

my ($count, $record, $ref, $select_clause, 
	$status, $value);
my ($access_code, $required_access_code);
my ($dbh, %dbhash, $debug, $dev_switch);

$| = 1;

my $regular_table_weight = 10;

print STDOUT ("Content-Type: text/html\n\n");

print STDOUT <<HEADER;
<html>
<head>
HEADER

unshift (@INC, "/data/www/usglobec/Scripts");
        require ('read_configuration_file.pl');
        require ('bob_setup.pl');
	require ('bob_unsetup.pl');


use lib '/data/www/usglobec/Scripts';
use MODEL_DB;

bob_setup();
my $date = scalar localtime;

$error = '<br>' . $error;
$warning = 'br' . $warning;

my @required_params = (
	'searchstring'
);

my @required_config_params = (
	'display_field_1',
	'mode'
);

my $config_file = $0;
$config_file =~ s!(.*)/.*!$1!;

$config_file = $config_file . '/' . 
		'search_for_model.config';

$status = read_configuration_file($config_file);

$status = 'okay';
foreach (@required_config_params) {
	unless (exists $config_param{$_} and 
		defined $config_param{$_} ) {
		MODEL_DB::sendmessage($error, 
	  		"$_ parameter not defined",
          		"");
		$status = 'ng';
	}
}

unless ($status eq 'okay' ) {
	MODEL_DB::sendmessage($error, 
	  "One or more required config parameters were not defined.",
          "Cannot continue.");
	goto END;
}

if (exists $config_param{'debug'} and defined $config_param{'debug'} ) {
        if ($config_param{'debug'} =~ m/^y/i or $config_param{'debug'} =~ m/^1/
                or $config_param{'debug'} =~ m/^t/i) {
          $debug = 'yes';
        }
        else { $debug = 'no'}
}
else { $debug = 'no'}

print STDOUT ("<p>***debug, config_file=$config_file<br>\n")
	if $debug eq 'yes';

get_web_form_data();

foreach $key (sort keys %param) {
        $param{$key} =~ s/ /_/g ;
        $param{$key} =~ s/\n/_/g ;
        $param{$key} =~ s/\t/_/g ;
        $param{$key} =~ s/\r/_/g ;
	print STDOUT ("<br>***debug, param{$key}=$param{$key}\n")
			if $debug eq 'yes';
}

$status = 'okay';
foreach (@required_params) {
	unless (exists $param{$_} and 
		defined $param{$_} ) {
		MODEL_DB::sendmessage($error, 
	  		"$_ form parameter not defined",
          		"");
		$status = 'ng';
	}
	else {
		print STDOUT ("<p>***debug, param{", $_,
			"}=", $param{$_}, "<br>\n")
			if $debug eq 'yes';
	}
}


if (exists $config_param{'mode'} and 
		defined $config_param{'mode'} ) {
        if ($config_param{'mode'} eq 'purgatory' ) {
                $dev_switch = 'purgatory';
        }
        elsif ($config_param{'mode'} eq 'live') {
                $dev_switch = 'live';
        }
        elsif ($config_param{'mode'} eq 'test') {
                $dev_switch = 'test';
        }
        else {
        
         MODEL_DB::sendmessage($error, 
          "<p>Mode=$config_param{'mode'} not correctly specified in config file.",
          "<br>Cannot continue.");
          goto END;
        }
}
else {
        MODEL_DB::sendmessage($error, "<p>Mode not specied.",
                "<br>Cannot continue.");
        goto END;
}

if ($dev_switch eq 'purgatory') {
	$goto_model_add_update = '<a href="http://www.usglobec.org/model.php">';
	$goto_model_display = '<a href="http://www.usglobec.org/model_display.php">';
	$goto_model_search = 
		'<a href="http://www.usglobec.org/specify_model_search_terms.html">';
        $dbh = MODEL_DB::connect_model_purgatory_login ();
        print STDOUT ("<p>***debug, selecting development database</p>\n")
                if $debug eq 'yes';
}
elsif ($dev_switch eq 'live') {
	$goto_model_add_update = '<a href="http://www.usglobec.org/model.php">';
	$goto_model_display = '<a href="http://www.usglobec.org/model_display.php">';
	$goto_model_search = 
		'<a href="http://www.usglobec.org/specify_model_search_terms.html">';
        $dbh = MODEL_DB::connect_model_login ();
        print STDOUT ("<p>***debug, selecting live database</p>\n")
                if $debug eq 'yes';
}
elsif ($dev_switch eq 'test') {
	$goto_model_add_update = '<a href="http://www.usglobec.org/model.php">';
	$goto_model_display = '<a href="http://www.usglobec.org/model_display.php">';
	$goto_model_search = 
		'<a href="http://www.usglobec.org/specify_model_search_terms.html">';
        $dbh = MOMDEL_DB::connect_model_purgatory_login ();
        print STDOUT ("<p>***debug, selecting test/purgatory database</p>\n")
                if $debug eq 'yes';
}
else {
	MODEL_DB::sendmessage($error, 
		"<p>Use mode=$dev_switch not correctly specified in config file.",
		"<br>Cannot continue.");
        exit (0);
}	

unless (defined $dbh) {
        MODEL_DB::sendmessage($error, 
         "<p>Could not connect to $dev_switch Model database",
         "<br>Error string=$DBI::errstr, and error=$DBI::err");
        exit (0);
}

print STDOUT <<HEADER1;
<title>Results of Model Search from 
the $dev_switch database</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
HEADER1


# Separate out search string words

my @search_words = MODEL_DB::parse_search_terms($param{'searchstring'}, $debug);

if ($#search_words < 0) {
	print STDOUT ("<p><b>No search word was entered.  Please ",
		"\nclick you browser's 'Back' button and try again.",
		"<br>\n");
	goto END;
}

print STDOUT (
	"<p>Your ",
		"search words/phrases were:<ul>\n");
foreach my $keyword (@search_words) {
	print STDOUT ("<li>$keyword</li><br>\n");
}
print STDOUT ("</ul>");

print STDOUT (
	"Select the model from the list below for which ",
	"you want to display<br>its informatino<p>\n");

my $added_weight;
my $key;
	
print STDOUT ("<p>***debug, just before call to search for $table table<br>\n")
	if $debug eq 'yes';

if ($dev_switch eq 'live') {
	$table = 'models';
}
else {
	$table = 'models_purg';
}
	
print STDOUT ("<p>***debug, just before call to search for $table table<br>\n")
		if $debug eq 'yes';
($status, $ids_ref) = &fast_search_of_table ($dbh, 
				$table, @search_words);
unless ($status =~ m/^okay/i) {
	print STDOUT ("<p>Error in performing table fast search, ",
		"Error=$status");
	goto END
}

@ids = @$ids_ref;
if (defined $ids[0]) {
	foreach $id (@ids) {
		if (defined $found{$id}) {
			$found{$id} = $found{$id} + $regular_table_weight;
			if ($found{$id} > 99) {$found{$id} = 99}
			$key = $found{$id} . ':' . $id;
			$found{$key} = $id;
		}
		else {
			$found{$id} = $regular_table_weight;
			$key = $regular_table_weight .':' .  $id;
			$found{$key} = $id;
		}
	}
}	

my $found = 'no';

print STDOUT ('<table border="1">');

my $i = 1;
$key = $display_field_ . $i;
print STDOUT ("<tr>\n");
while (exists $config_param{$key} and defined $config_param{$key} ) {
	if (exists $config_param{$config_param{$key}} and defined 
			$config_param{$config_param{$key}} ) {
		$heading = $config_param{$config_param{$key}};
	}
	else {
		$heading = $config_param{$key};
	}
	print STDOUT ('<th>', $heading, "</th>\n");
	$i++;
	$key = $display_field_ . $i;
}

print STDOUT ("</tr>\n<tr>\n");

my $numb_columns = $i - 1;	
foreach $key (sort byweight keys %found) {
	unless ($key =~ m/^\d+:/) {next;}
	$found = 'yes';
	$id = $found{$key};
	unless (exists $used{$id} and defined $used{$id}) {
		$used{$id} = 'yes';
		my $hash_ref = MODEL::get_record_by_id($dbh, $id);
		my $hash = %$hash_ref;
		for (my $j=1; $j<=$numb_columns; $j++) {
			$hash_key = $display_field_ . $j;
			if (exists $hash{$hash_key}) {
				unless (defined $hash{$hash_key} ) {
					$value = "";
				}
				else {
					$value = $hash{$hash_key};
				}
				$value = 
				   '<a href="http://www.usglobec.org/model_display.php?ind=' .
				   $id . ' target="_blank">' . $value . "</a>\n"
					unless $value eq "";
			}
			else {
				$value = "";
			}
			print STDOUT ("<td>", $value, "<td>");
		}
	}
	print STDOUT ("</tr>\n");
}
print STDOUT ("</table>\n");

END:

if (defined $dbh) {$dbh -> disconnect;}

http://www.usglobec.org/images/menu/Home.png
http://www.usglobec.org/search_icon.jpg

print STDOUT ('<p><a href="', $goto_model_search, 
	">Do another search</a></p><p>\n",
	'<p><a href="', $goto_model_add_update, 
	"></a></p><p>\n",
$goto_model_add_update = 
	$goto_model_display = 
	 =


my $prog = $0;
$prog =~ s/.*\/(.*)/$1/;
print STDOUT ('<p><font size="-6">',
	"<hr><i>Program $prog, Version $version<br>\n");
print STDOUT (
	"Page generated $date for the $dev_switch database</font></p>\n");
print STDOUT ("</body>\n</html>\n");

bob_unsetup();
exit;

#----------------------------------------------------------------------------------

sub byweight {

# Assumes values passed are in the following format:
#
#	NN:<table id (primary key).

# where NN is a two digit number and we want to sort such
# that the higher numbers come first.  If the two numbers
# are the same then sort the rest alphabetically;

unless ($a =~ m/^\d+/ ) {
	return -1;
}
unless ($b =~ m/^\d+/ ) {
	return -1;
}

my $a_value = $a;
my $b_value = $b;
my $a_string = $a;
my $b_string = $b;

$a_value =~ s/^(\d+).*/$1/;
$b_value =~ s/^(\d+).*/$1/;

$a_string =~ s/^\d+(.*)/$1/;
$b_string =~ s/^\d+(.*)/$1/;

if ($a_value < $b_value) {
	return 1;
}
elsif ($a_value == $b_value) {
	return $a_string cmp $b_string;
}
else {
	return -1;
}
}
