#!/usr/bin/perl -w

#use strict;

use DBI;
use Config::IniFiles;
use Switch;

#functions common to both interactionPathsFromSif and interactionPathsFromTsv are in this perl script file
require "interactionPath.pl";

#use constant SITE_ADJECTIVE => ($ENV{'DevelopmentSite'} ? 'Development': 'Live');
use constant SITE_ADJECTIVE => 'Development';


############First various sub routines are defined.############ 
############Following it the main subroutine code is at the botton of the file############


sub showUsage(){
	print "Usage: \n\tperl interactionPathsFromTsv <option> <fileName>\n";
	print "options:\n\t";
	print "1 - to import gene id data\n\t";
	print "2 - to import seed interaction data\n\t";	
}

#imports the tab separated file containing seed interaction 
sub importSeedInteractionData(){
	print "reading seed interaction information from file\n";

	open(interactions_file, "$fileName") || die "Error: file '$fileName' can not be opened\n";
	while(<interactions_file>){
		my $entry = $_;
		
		# strip off newline characters
		chomp $entry;
		$entry =~ s/\r//g;
      $entry =~ s/\n//g;
      
      # split the columns into separate variables
      my ($obj_abbr_left,$int_type_left,$mode_of_action,$obj_abbr_right,$int_type_right,$interaction_type,$evidence,$evidence_code,$experiment,$comments) = split("\t", $entry);
      
      #skip
     	next if(isEmpty($obj_abbr_left));
      
      #get ids(primary keys) from other tables
      $obj_id_left = getObjectIdFromAbbreviation($obj_abbr_left);
      $obj_id_right = getObjectIdFromAbbreviation($obj_abbr_right);
      $interaction_type_id = getInteractionTypeId($interaction_type);
     	
     	#if any of the above values are empty, print a message and move to the next line
		if(isEmpty($obj_id_left)){
			print "$obj_abbr_left was not found in the db. Skipping this line\n";
			next;
		}
		elsif(isEmpty($obj_id_right)){
			print "$obj_abbr_right was not found in the db. Skipping this line\n";
			next;
		}
		elsif(isEmpty($interaction_type_id)){
			print "$interaction_type was not found in the db. Skipping this line\n";
			next;
		}
		
		#get various primary ids from the table.      
      $int_type_id_left = getInteractorTypeId($int_type_left);
      $int_type_id_right = getInteractorTypeId($int_type_right);
      $mode_of_action_id = getModeOfActionId($mode_of_action);
      $evidence_id = getEvidenceId($evidence);
      $evidence_code_id = getEvidenceCodeId($evidence_code);
      $experiment_id = getExperimentId($experiment);
      
      #get interaction_id to see if already exists
     	$interaction_id = getInteractionId($obj_id_left,$interaction_type_id,$obj_id_right,$curator_id);
     	print "interaction_id:$interaction_id\n";
     	#if not, insert data into to the database
     	if(isEmpty($interaction_id)){
      		$query = "INSERT INTO Interaction(`object_id_left`,`object_id_right`,`interaction_type_id`,`mode_of_action_id`,
      	`interactor_type_id_left`,`interactor_type_id_right`,`evidence_id`,`evidence_code_id`,`experiment_id`,`comments`,`curator_id`,`date`) 
      	VALUES ('$obj_id_left','$obj_id_right','$interaction_type_id','$mode_of_action_id','$int_type_id_left','$int_type_id_right'
      	,'$evidence_id','$evidence_code_id','$experiment_id','$comments','$curator_id', '".strftime("%Y-%m-%d", localtime)."')";      
      		executeDbQuery($query);
      }				
	}
}

sub importGeneInformation(){
	print "reading gene information from file\n";
	open(gene_file, "$fileName") || die "Error: file '$fileName' can not be opened\n";
	while(<gene_file>){
		my $entry = $_;
		
		# strip off newline characters
		chomp $entry;
		$entry =~ s/\r//g;
    $entry =~ s/\n//g;
      
      my ($accession, $is_gene,$is_metabolite,$symbol,$full_name,$synonym,$species_name,$ncbi_id) = split("\t", $entry);
      
      #skip the line if accession value is empty
      next if(isEmpty($accession));
      
      $object_type=1;
		if($is_metabolite eq "yes"){
			$object_type=2;
			}
		
		#get species id, if the species is not present already, insert it
		$species_id = getSpeciesId($species_name,$ncbi_id);
		if(isEmpty($species_id)){
			if(!isEmpty($ncbi_id)){
				$query = "INSERT INTO Species(`species`,`NCBI_taxonomy_id`) VALUES ('$species_name','$ncbi_id')";
			}
			else{
				$query = "INSERT INTO Species(`species`) VALUES ('$species_name')";
			}
			executeDbQuery($query);
			$species_id = getSpeciesId($species_name,$ncbi_id);
			print "New species $species_name added to the db\n";
		}
		
		#gets synonym_id. The function returns the id if exists already. else, inserts synonym and returns the id.
		$synonym_id = getSynonymId($synonym);
		print "synonym_id:$synonym_id\t";
		
		#construct the query and insert object information to the table.
		$query = "INSERT INTO Object(`object_accession`,`species_id`,`object_full_name`,`object_abbreviation`,`object_type_id`) VALUES('$accession','$species_id','$full_name','$symbol','$object_type') ON DUPLICATE KEY UPDATE object_accession='$accession' ";
		if(!isEmpty($full_name)){
			$query = $query." , object_full_name='$full_name'";	
		}
		if(!isEmpty($full_name)){
			$query = $query." , object_abbreviation='$symbol'";
		}
		if(!isEmpty($object_type)){
			$query = $query." , object_type_id='$object_type'";	
		}
		executeDbQuery($query);
		$object_id = getObjectIdFromAccession($accession);
		print "object id: $object_id\n";
		#next, insert object_id and synonym_id into object_synonym table.
		$query = "INSERT INTO Object_synonym(`object_id`,`synonym_id`) VALUES ('$object_id','$synonym_id')";
		executeDbQuery($query);
	}

}


if($#ARGV != 1){
	print "Invalid inputs\n";
	showUsage();
	die;
}

$optionId = $ARGV[0];
$fileName = $ARGV[1];
$curatorId = "";

switch($optionId){
	#import gene information - accession id, synonym etc
   case "1"
	{
	   importGeneInformation();
	}
	#import interaction data
	case "2"
	{
		$curatorId = getCuratorId(getCuratorProperties());
		importSeedInteractionData();
	}
	else{
		showUsage();	
	}
	
}
