#!/usr/local/bin/perl

###############################################################################
# Program     : GetBioentities
# Author      : Eric Deutsch <edeutsch@systemsbiology.org>
# $Id: GetBioentities 3243 2005-03-21 09:02:00Z edeutsch $
#
# Description : This program that allows users to
#               browse through the list of bioentities in the database
#
# SBEAMS is Copyright (C) 2000-2005 Institute for Systems Biology
# This program is governed by the terms of the GNU General Public License (GPL)
# version 2 as published by the Free Software Foundation.  It is provided
# WITHOUT ANY WARRANTY.  See the full description of GPL terms in the
# LICENSE file distributed with this software.
#
###############################################################################


###############################################################################
# Set up all needed modules and objects
###############################################################################
use strict;
use Getopt::Long;
use FindBin;

use lib "$FindBin::Bin/../../lib/perl";
use vars qw ($sbeams $sbeamsMOD $q $current_contact_id $current_username
             $PROG_NAME $USAGE %OPTIONS $QUIET $VERBOSE $DEBUG $DATABASE
             $TABLE_NAME $PROGRAM_FILE_NAME $CATEGORY $DB_TABLE_NAME
             @MENU_OPTIONS);

use SBEAMS::Connection qw($q);
use SBEAMS::Connection::Settings;
use SBEAMS::Connection::Tables;

use SBEAMS::Interactions;
use SBEAMS::Interactions::Settings;
use SBEAMS::Interactions::Tables;

$sbeams = new SBEAMS::Connection;
$sbeamsMOD = new SBEAMS::Interactions;
$sbeamsMOD->setSBEAMS($sbeams);
$sbeams->setSBEAMS_SUBDIR($SBEAMS_SUBDIR);


#use CGI;
#$q = new CGI;


###############################################################################
# Set program name and usage banner for command like use
###############################################################################
$PROG_NAME = $FindBin::Script;
$USAGE = <<EOU;
Usage: $PROG_NAME [OPTIONS] key=value kay=value ...
Options:
  --verbose n         Set verbosity level.  default is 0
  --quiet             Set flag to print nothing at all except errors
  --debug n           Set debug flag

 e.g.:  $PROG_NAME [OPTIONS] [keyword=value],...

EOU

#### Process options
unless (GetOptions(\%OPTIONS,"verbose:s","quiet","debug:s")) {
  print "$USAGE";
  exit;
}

$VERBOSE = $OPTIONS{"verbose"} || 0;
$QUIET = $OPTIONS{"quiet"} || 0;
$DEBUG = $OPTIONS{"debug"} || 0;
if ($DEBUG) {
  print "Options settings:\n";
  print "  VERBOSE = $VERBOSE\n";
  print "  QUIET = $QUIET\n";
  print "  DEBUG = $DEBUG\n";
}


###############################################################################
# Set Global Variables and execute main()
###############################################################################
main();
exit(0);


###############################################################################
# Main Program:
#
# Call $sbeams->Authenticate() and exit if it fails or continue if it works.
###############################################################################
sub main {

  #### Do the SBEAMS authentication and exit if a username is not returned
  exit unless ($current_username = $sbeams->Authenticate(
    #permitted_work_groups_ref=>['Interactions_user','Interactions_admin',
    #  'Interactions_readonly'],
    #connect_read_only=>1,
    #allow_anonymous_access=>1,
  ));


  #### Read in the default input parameters
  my %parameters;
  my $n_params_found = $sbeams->parse_input_parameters(
    q=>$q,parameters_ref=>\%parameters);
  #$sbeams->printDebuggingInfo($q);


  #### Process generic "state" parameters before we start
  $sbeams->processStandardParameters(parameters_ref=>\%parameters);


  #### Decide what action to take based on information so far
  if ($parameters{action} eq "???") {
    # Some action
  } else {
    $sbeamsMOD->printPageHeader();
    handle_request(ref_parameters=>\%parameters);
    $sbeamsMOD->printPageFooter();
  }


} # end main


###############################################################################
# Handle Request
###############################################################################
sub handle_request {
  my %args = @_;


  #### Process the arguments list
  my $ref_parameters = $args{'ref_parameters'}
    || die "ref_parameters not passed";
  my %parameters = %{$ref_parameters};


  #### Define some generic varibles
  my ($i,$element,$key,$value,$line,$result,$sql);


  #### Define some variables for a query and resultset
  my %resultset = ();
  my $resultset_ref = \%resultset;
  my (%url_cols,%hidden_cols,%max_widths,$show_sql);


  #### Read in the standard form values
  my $apply_action  = $parameters{'action'} || $parameters{'apply_action'};
  my $TABLE_NAME = $parameters{'QUERY_NAME'};


  #### Set some specific settings for this program
  my $CATEGORY="Browse Bioentities";
  $TABLE_NAME="IN_GetBioentities" unless ($TABLE_NAME);
  ($PROGRAM_FILE_NAME) =
    $sbeamsMOD->returnTableInfo($TABLE_NAME,"PROGRAM_FILE_NAME");
  my $base_url = "$CGI_BASE_DIR/$SBEAMS_SUBDIR/$PROGRAM_FILE_NAME";


  #### Get the columns and input types for this table/query
  my @columns = $sbeamsMOD->returnTableInfo($TABLE_NAME,"ordered_columns");
  my %input_types = 
    $sbeamsMOD->returnTableInfo($TABLE_NAME,"input_types");


  #### Read the input parameters for each column
  my $n_params_found = $sbeams->parse_input_parameters(
    q=>$q,parameters_ref=>\%parameters,
    columns_ref=>\@columns,input_types_ref=>\%input_types);


  #### If the apply action was to recall a previous resultset, do it
  my %rs_params = $sbeams->parseResultSetParams(q=>$q);
  if ($apply_action eq "VIEWRESULTSET") {
    $sbeams->readResultSet(resultset_file=>$rs_params{set_name},
        resultset_ref=>$resultset_ref,query_parameters_ref=>\%parameters);
    $n_params_found = 99;
  }


  #### Set some reasonable defaults if no parameters supplied
  unless ($n_params_found) {
  }


  #### Apply any parameter adjustment logic
  # none


  #### Display the user-interaction input form
  $sbeams->display_input_form(
    TABLE_NAME=>$TABLE_NAME,CATEGORY=>$CATEGORY,apply_action=>$apply_action,
    PROGRAM_FILE_NAME=>$PROGRAM_FILE_NAME,
    parameters_ref=>\%parameters,
    input_types_ref=>\%input_types,
  );


  #### Display the form action buttons
  $sbeams->display_form_buttons(TABLE_NAME=>$TABLE_NAME);


  #### Finish the upper part of the page and go begin the full-width
  #### data portion of the page
  $sbeams->display_page_footer(close_tables=>'YES',
    separator_bar=>'YES',display_footer=>'NO');



  #########################################################################
  #### Process all the constraints

  #### Build ORGANISM_ID constraint
  my $organism_clause = $sbeams->parseConstraint2SQL(
    constraint_column=>"O.organism_id",
    constraint_type=>"int_list",
    constraint_name=>"Organisms",
    constraint_value=>$parameters{organism_id} );
  return if ($organism_clause eq '-1');


  #### Build BIOENTITY EXACT NAME constraint
  my $bioentity_exact_name_clause = $sbeams->parseConstraint2SQL(
    constraint_column=>"bioentity_common_name",
    constraint_type=>"plain_text",
    constraint_name=>"BioEntity Exact Name",
    constraint_value=>$parameters{bioentity_exact_name} );
  return if ($bioentity_exact_name_clause eq '-1');

  #### Translate to look in both common and canonical
  while ($bioentity_exact_name_clause =~ /(bioentity_common_name LIKE '.+?')/) {
    my $orig = $1;
    my $new1 = $orig;
    my $new2 = $orig;
    my $new3 = $orig;
    $new1 =~ s/common/xxyyzz/;
    $new2 =~ s/common/canonical/;
    $new3 =~ s/common/aliases/;
    $new3 =~ s/_name//;
    $bioentity_exact_name_clause =~ s/$orig/( BE.$new1 OR BE.$new2 OR BE.$new3 )/;
  }
  $bioentity_exact_name_clause =~ s/xxyyzz/common/g;


  #### If there are no wildcards in the fragment, then add them
  my $bioentity_search_fragment = $parameters{bioentity_search_fragment};
  if ($bioentity_search_fragment) {
    unless ($bioentity_search_fragment =~ /\%/) {
      $bioentity_search_fragment = "\%$bioentity_search_fragment\%";
    }
  }

  #### Build BIOENTITY SEARCH FRAGMENT constraint
  my $bioentity_search_fragment_clause = $sbeams->parseConstraint2SQL(
    constraint_column=>"bioentity_common_name",
    constraint_type=>"plain_text",
    constraint_name=>"BioEntity Search Fragment",
    constraint_value=>$bioentity_search_fragment );
  return if ($bioentity_search_fragment_clause eq '-1');
 
  #### Translate to look in several places
  while ($bioentity_search_fragment_clause =~ /(bioentity_common_name LIKE '.+?')/) {
    my $orig = $1;
    my $new1 = $orig;
    my $new2 = $orig;
    my $new3 = $orig;
    my $new4 = $orig;
    $new1 =~ s/common/xxyyzz/;
    $new2 =~ s/common/canonical/;
    $new3 =~ s/common/full/;
    $new4 =~ s/common/aliases/;
    $new4 =~ s/_name//;
    $bioentity_search_fragment_clause =~ s/$orig/( BE.$new1 OR BE.$new2 OR BE.$new3 OR BE.$new4 )/;
  }
  $bioentity_search_fragment_clause =~ s/xxyyzz/common/g;


  #### Build ROWCOUNT constraint
  $parameters{row_limit} = 50000
    unless ($parameters{row_limit} > 0 && $parameters{row_limit}<=1000000);
  my $limit_clause = $sbeams->buildLimitClause(
   row_limit=>$parameters{row_limit});


  #### Define some variables needed to build the query
  my @column_array;
  my @additional_columns = ();


  #### Define the desired columns in the query
  #### [friendly name used in url_cols,SQL,displayed column title]

  @column_array = (
    ["bioentity_id","BE.bioentity_id","Bioentity ID"],
    ["organism", "O.full_name", "BioEntity 1 Organism"],
    ["bioentity_type", "BET.bioentity_type_name", "BioEntity 1 Type"],
    ["geneID", "BE.geneID", "Bioentity GeneID"],
    ["bioentity_common_name","BE.bioentity_common_name","BioEntity 1 Common Name"],
    ["bioentity_canonical_name","BE.bioentity_canonical_name","BioEntity 1 Canonical Name"],
    ["bioentity_full_name","BE.bioentity_full_name","BioEntity 1 Full Name"],
    ["bioentity_aliases","BE.bioentity_aliases","BioEntity 1 Aliases"],
    ["biosequence_name","BS.biosequence_name","BioEntity 1 Biosequence Name"],
    ["comment","BE.comment","BioEntity 1 Comment"],
    @additional_columns,
  );
		
				
  #### Set flag to display SQL statement if user selected
  if ( $parameters{display_options} =~ /ShowSQL/ ) {
    $show_sql = 1;
  }


  #### Build the columns part of the SQL statement
  my %colnameidx = ();
  my @column_titles = ();
  my $columns_clause = $sbeams->build_SQL_columns_list(
    column_array_ref=>\@column_array,
    colnameidx_ref=>\%colnameidx,
    column_titles_ref=>\@column_titles
  );


  #### Build the query
  $sql = qq~
    SELECT $limit_clause->{top_clause} $columns_clause
      FROM $TBIN_BIOENTITY BE
      LEFT JOIN $TB_ORGANISM O ON ( BE.organism_id = O.organism_id )
      LEFT JOIN $TBIN_BIOENTITY_TYPE BET ON ( BE.bioentity_type_id = BET.bioentity_type_id )
      LEFT JOIN $TBIN_BIOSEQUENCE BS ON (BE.biosequence_id = BS.biosequence_id )
     WHERE BE.record_status != 'D'
       AND ( O.record_status != 'D' OR O.record_status IS NULL )
       AND ( BET.record_status != 'D' OR BET.record_status IS NULL )
     $organism_clause
     $bioentity_exact_name_clause
     $bioentity_search_fragment_clause
     $limit_clause->{trailing_limit_clause}
    ~;


  #### Certain types of actions should be passed to links
  my $pass_action = "QUERY";
  $pass_action = $apply_action if ($apply_action =~ /QUERY/i);


  #### Pass nearly all of the constraints down to a child query
  my @parameters_to_pass;
  my $parameters_list = '';
  while ( ($key,$value) = each %input_types ) {
    if ($key ne 'display_options' &&
        $key ne 'n_occurrences' &&
        $key ne 'biosequence_name_constraint' &&
        $key ne 'xx_constraint'
      ) {
      if ($parameters{$key}) {
        push(@parameters_to_pass,"$key=$parameters{$key}");
      }
    }
  }
  if (@parameters_to_pass) {
    $parameters_list = join('&',@parameters_to_pass);
  }


  #### Define the hypertext links for columns that need them
  %url_cols = (
    	       'Bioentity ID' => "$CGI_BASE_DIR/$SBEAMS_SUBDIR/ManageTable.cgi?TABLE_NAME=IN_bioentity&bioentity_id=\%V",
    	       'Bioentity ID_ATAG' => 'TARGET="Win1"',
               
    	       'Bioentity GeneID' => "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=gene&cmd=retrieve&dopt=grahics&list_uids=\%V",
    	       'Bioentity Gene ID_ATAG' => 'TARGET="Win1"',
               
             
  );
#http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?DB=gene&cmd=retrieve&dopt=graphics&list_uids=12111
#http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=gene&cmd=Display&dopt=gene_cdd&from_uid=11122
  #### Define columns that should be hidden in the output table
  %hidden_cols = ('BioEntity 1 ID' => 1,
		  'BioEntity 2 ID' => 1,
		 );


  unless ( $parameters{display_options} =~ /ShowReg/) {
    %hidden_cols = ( %hidden_cols,
                     'Regulatory Feature 1 Name' => 1,
                     'Regulatory Feature 2 Name' => 1,
                     'bioentity1_url' => 1,
                     'bioentity2_url' => 1,
		     'publication_url'=> 1,
		     'interaction_group_id'=> 1,
		     'interaction_group_name'=> 1,
		     'project_id'=> 1,
    );
  }



  #########################################################################
  #### If QUERY or VIEWRESULTSET was selected, display the data
  if ($apply_action =~ /QUERY/i || $apply_action eq "VIEWRESULTSET") {

    #### If the action contained QUERY, then fetch the results from
    #### the database
    if ($apply_action =~ /QUERY/i) {

      #### Show the SQL that will be or was executed
      $sbeams->display_sql(sql=>$sql) if ($show_sql);

      print STDERR "$sql\n";
      #### Fetch the results from the database server
      $sbeams->fetchResultSet(
        sql_query=>$sql,
        resultset_ref=>$resultset_ref,
      );

      #### Store the resultset and parameters to disk resultset cache
      $rs_params{set_name} = "SETME";
      $sbeams->writeResultSet(
        resultset_file_ref=>\$rs_params{set_name},
        resultset_ref=>$resultset_ref,
        query_parameters_ref=>\%parameters,
        resultset_params_ref=>\%rs_params,
        query_name=>"$SBEAMS_SUBDIR/$PROGRAM_FILE_NAME",
      );
    }

    #### Display the resultset
    $sbeams->displayResultSet(
      resultset_ref=>$resultset_ref,
      query_parameters_ref=>\%parameters,
      rs_params_ref=>\%rs_params,
      url_cols_ref=>\%url_cols,
      hidden_cols_ref=>\%hidden_cols,
      max_widths=>\%max_widths,
      column_titles_ref=>\@column_titles,
      base_url=>$base_url,
    );


    #### Display the resultset controls
    $sbeams->displayResultSetControls(
      resultset_ref=>$resultset_ref,
      query_parameters_ref=>\%parameters,
      rs_params_ref=>\%rs_params,
      base_url=>$base_url,
    );


  #### If QUERY was not selected, then tell the user to enter some parameters
  } else {
    if ($sbeams->invocation_mode() eq 'http') {
      print "<H4>Select parameters above and press QUERY</H4>\n";
    } else {
      print "You need to supply some parameters to contrain the query\n";
    }
  }


} # end handle_request



###############################################################################
# evalSQL
#
# Callback for translating Perl variables into their values,
# especially the global table variables to table names
###############################################################################
sub evalSQL {
  my $sql = shift;

  return eval "\"$sql\"";

} # end evalSQL

