#!/usr/bin/perl
if ($0 =~ /([^(\/)]+)$/) {
    push (@INC, "$`lib/");
    push (@INC, "$`../ws_clients/perl_clients/RSATWS/");
}
require "RSA.lib";
require RSAT::Tree;
require RSAT::TreeNode;
require RSAT::OrganismManager;
#use strict;


## Initialize parameters
local $start_time = &RSAT::util::StartScript();

## Main RSAT server for the option -server
## WSDL  Web services
$from_server = 0;

## Ouptut formats
$out_format = "tab";
@supported_formats = qw (tab tree html_tree);
foreach $f (@supported_formats) {
    $supported_format{$f} = 1;
}
$supported_formats = join ",", @supported_formats;

## Return fields
$return_fields = "";
@return_fields = ();
@supported_return_fields = @RSAT::OrganismManager::supported_org_fields;
%supported_return_fields = ();
foreach my $field (@supported_return_fields) {
    $supported_return_fields{$field} = 1;
}
$supported_return_fields = join ",", @supported_return_fields;

## Taxon
my $taxon = "";

## Read arguments
&ReadArguments();


################################################################
## If it does not exist yet, create a table with the supported
## organisms
##
## This is a tricky way to fix the transition from the
## Perl-script-based loading to the tab-delimited text file-based
## loding.  In principe this piece of code should run only once per
## server, and then be suppressed.
# unless (-e $ENV{RSAT}."/public_html/data/supported_organisms.tab") {
#   &RSAT::message::Warning("supported_organisms.tab is missing, regenerating from the .pl files");
#   ## Load organisms from the (obsolete) Perl file supported_organisms.pl
#   my $perl_organisms = $ENV{RSAT}."/public_html/data/supported_organisms.pl";
#   if (-e $perl_organisms) { 
#     &RSAT::message::Warning("Loading organisms from file", $perl_organisms);
#    require $perl_organisms;
#   }
#   my $perl_organisms_ensembl = $ENV{RSAT}."/public_html/data/supported_mammals.pl";
#   if (-e $perl_organisms_ensembl) {
#     &RSAT::message::Warning("Loading organisms from file", $perl_organisms_ensembl);
#     require $perl_organisms_ensembl;
#   }
#   ## Export organism table in tab format for future queries
#   $verbose = $verbose || 1; ## in order to give the warning with the export.
#   &RSAT::OrganismManager::export_supported_organisms();
# }

## Load the list of supported organisms
#&RSAT::OrganismManager::load_supported_organisms();

## Return fields
if ($out_format eq "full") {
    @return_fields = @supported_return_fields;
}
if (scalar(@return_fields) == 0) {
    @return_fields = ("ID");
}

## Open the output stream
$out = &OpenOutputFile($outfile{output});

################################################################
## Get the list supported organisms from a remote RSAT server
if ($from_server) {
  ## Required for the option -server (obtaining the supported organisms from a remote server)
  require MyInterfaces::RSATWebServices::RSATWSPortType;
  require SOAP::WSDL; ## Requires version 2.0 or later of SOAP::WSDL

  ## Service call
  my $soap=MyInterfaces::RSATWebServices::RSATWSPortType->new();

  ## Output option
  my $output_choice = 'client';  ## Accepted values: 'server', 'client', 'both'

  ## Retrieve-seq parameters
  my %args = (
	      'taxon' => $taxon,
	      'format'=> $out_format,
	      'return'=> $return_fields,
	     );

  ## Send the request to the server
  &RSAT::message::Info("Sending request to the remote server") if ($main::verbose >= 1);
  my $som = $soap->supported_organisms({'request' => \%args});

  ## Get the result
  if ($som) {
    my $results = $som->get_response();

    ## Report the remote command
    my $command = $results -> get_command();
    &RSAT::message::Info("Command used on the server:\n;\t".$command) if ($main::verbose >= 1);

    ## Report the result
    my $result = $results -> get_client();
    print $out $result;
  } else {
    &RSAT::error::FatalError("Web services. A fault (%s) occured : %s\n", $som->get_faultcode(), $som->get_faultstring());
  }

  exit();
}

if (($out_format eq "tree")||($out_format eq "html_tree")) {
    ## Create a tree with the taxonomy
    my $tree = new RSAT::Tree();
    $tree->LoadSupportedTaxonomy("Organisms", \%main::supported_organism);
#    print $out join("\n","--",$taxon,$out_format,"all",undef)."\n";
    print $out $tree->as_indented_text("--",$taxon,$out_format,"all",undef);

 } else {
   print $out &RSAT::OrganismManager::supported_organism_table($verbose, 0, $taxon, @return_fields); ## Export the table with header and absolute paths
}


################################################################
## Report execution time and close output stream
my $exec_time = &RSAT::util::ReportExecutionTime($start_time); ## This has to be exectuted by all scripts
print $main::out $exec_time if ($main::verbose >= 1); ## only report exec time if verbosity is specified
close $main::out if ($main::outfile{output});

exit(0);

################################################################
##################### SUBROUTINE DEFINITION ####################
################################################################



################################################################
#### Display full help message
sub PrintHelp {
  open HELP, "| more";
  print HELP <<End_of_help;
NAME
	supported-organisms

USAGE
        supported-organisms [-i inputfile] [-o outputfile] [-v]

AUTHORS
	Jacques.van.Helden@ulb.ac.be

	Management of taxonomic tree: 
	   Rekin's Janky (rekins@bigre.ulb.ac.be).

DESCRIPTION

	Returns the list of organisms supported on the local
	Regulatory Sequence Analysis Tools (default) or on a remote
	server (option -server). The list can be restricted at a given
	taxonomic level (option -taxon).

CATEGORY
	Data management.

OPTIONS
	-h	(must be first argument) display full help message

	-help	(must be first argument) display options

	-format	output format
		supported: $supported_formats

		tab: tab-delimited text format, with one row per
		organism and one column per field (see option
		-return).

		tree: a textual representation of the tree, with
		hyphen-based indentation to indicate taxon depth.

		html_tree: same as tree, but wiht HTML tags (organism
		names in italics, taxon names in bold).

 	-return output fields
		supported: $supported_return_fields

        -taxon selected_taxon 
	       Only returns organisms belonging to a selected taxon.

	-server Return the list of organisms supported on a remote
		RSAT server, via the Web services interface
		(http://rsat.ulb.ac.be/rsat/web_services).  

		The option -server can be combined with the option
		-taxon in order to obtain the list of organisms
		supported on the main RSAT server, before downloading
		them.

		Ex: supported-organisms -taxon Fungi -server

		This option requires a proper installation of the
		SOAP::WSDL module.
End_of_help
  close HELP;
  exit;
}

################################################################
#### Display short help message #####
sub PrintOptions {
  open HELP, "| more";
  print HELP <<End_short_help;
template options
----------------
-h	(must be first argument) display full help message
-help	(must be first argument) display options
-i	input file
-o	output file
-v	verbose
-format	output format ($supported_formats)
-return output fields ($supported_return_fields)
-taxon  selected_taxon
-server return organisms supported on the remote RSAT server.
End_short_help
  close HELP;
  exit;
}


################################################################
#### Read arguments 
sub ReadArguments {
  foreach my $a (0..$#ARGV) {
    ### verbose ###
    if ($ARGV[$a] eq "-v") {
      if (&IsNatural($ARGV[$a+1])) {
	$verbose = $ARGV[$a+1];
      } else {
	$verbose = 1;
      }

      ### detailed help
    } elsif ($ARGV[$a] eq "-h") {
      &PrintHelp;

      ### list of options
    } elsif ($ARGV[$a] eq "-help") {
      &PrintOptions;

      ### output format
    } elsif ($ARGV[$a] eq "-format") {
      $out_format = $ARGV[$a+1];
      unless ($supported_format{$out_format}) {
	&RSAT::error::FatalError("Invalid format", $out_format, "Supported:".$supported_formats);
      }

      ### output format
    } elsif ($ARGV[$a] eq "-format") {
      $out_format = $ARGV[$a+1];
      unless ($supported_format{$out_format}) {
	&RSAT::error::FatalError("Format $out_format is not supported\n");
      }

      ### output format
    } elsif ($ARGV[$a] eq "-server") {
	$from_server = 1;

      #### return fields
    } elsif ($ARGV[$a] eq "-return") {
	$return_fields = $ARGV[$a+1];
	chomp($return_fields);
	my @fields_to_return = split ",", $return_fields;
	foreach $field (@fields_to_return) {
	    if ($supported_return_fields{$field}) {
		push @return_fields, $field;
	    } else {
		&RSAT::error::FatalError(join("\t", $field, "Invalid return field. Supported:", $supported_return_fields));
	    }
	}

      ### root taxon
    } elsif ($ARGV[$a] eq "-taxon") {
      $taxon = $ARGV[$a+1];

      ### output file  
    } elsif ($ARGV[$a] eq "-o") {
      $outfile{output} = $ARGV[$a+1];

    }
  }
}

