#!/usr/bin/perl

use pathgen;
use CGI qw/:standard/;
use DBI;
use strict;
$CGI::POST_MAX = 1024 * 5000; # No file uploads over 5MB

my $DBNAME = "pathways_dev";
my $DBHOSTNAME = "bioresearch.byu.edu";
my $DBUSERNAME = "phylo";
my $DBPASSWORD = "";

my $DBJOBTABLE = "jobs"; # CREATE TABLE jobs(pid INT NOT NULL AUTO_INCREMENT, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, processed TIMESTAMP DEFAULT 0, completed TIMESTAMP DEFAULT 0, commands TEXT, ip TEXT, PRIMARY KEY (pid));


my $tbStartName = 'tbStartGenes';
my $tbTargetName = 'tbTargetGenes';
my $tbRows = 10; #Number of rows in the Start/Target Genes textboxes
my $tbPathsName = 'tbAdditionalPaths';
my $tbLookupName = 'tbGeneLookup';
my $tbHiddenTaxa = 'tbHiddenTaxa';
my $btnFindName = 'Add Genes Associated With:';
my $btnSubmitName = 'Submit Job';
my $tbGotoJobName = 'tbGotoJob';
my $btnGotoJobName = 'btnGotoJob';

my $OUTPUTDIR = "temp";
my $REFRESHTIME = "5";
my $IMAGEFOLDER = "/pathgen/Images";
my $PATHTOEMAIL = "/pathgen/requestEmail.cgi";
my $IPLOGFILE = "ipLog";

if (!param)
{
	print pathgen->myheader();
	print pathgen->wrapper_start();
#	print "<h3>This site is currently under maintenance (25 August 2009 6:53MST). If your request does not work, please try again in a few hours.</h3>";
	print_default_form();
	print pathgen->wrapper_end();	
}

if (param($btnSubmitName))
{
	print pathgen->myheader();
	print pathgen->wrapper_start();
	my $jobId = get_jobId();
	create_input_files($jobId);
	create_job($jobId);
	print_redirect($jobId);
	get_expr_upload($jobId);
	print pathgen->wrapper_end();
}


# methods

sub create_input_files #(jobId)
{
	my $jobId = shift;

	system("mkdir $OUTPUTDIR/job$jobId");
	chmod(0775, "$OUTPUTDIR/job$jobId");
	system("chgrp undergrad $OUTPUTDIR/job$jobId");
	my $tempPath = "$OUTPUTDIR/job$jobId/";
	my $startGeneString = param($tbStartName);
    $startGeneString =~ s/^\s+//;
    my @startGeneList = split /\s+/, $startGeneString;
    open STARTFILE, ">$tempPath"."startgenes.txt";
    foreach(@startGeneList) {
        my $upper = uc($_);
        $upper =~ tr///;
        print STARTFILE $upper, "\n";
    }
    close STARTFILE;

	my $targetGeneString = param($tbTargetName);
    $targetGeneString =~ s/^\s+//;
    my @targetGeneList = split /\s+/, $targetGeneString;
    open TARGETFILE, ">$tempPath"."targetgenes.txt";
    foreach(@targetGeneList) {
        my $upper = uc($_);
        $upper =~ tr///;
        print TARGETFILE $upper, "\n";
    }
    close TARGETFILE;
	
	#parse all additional interactions, creating a list of these interactions
    my $geneText = param($tbPathsName);
    $geneText =~ s/^\s+//;
    my @interactionsList = split /[\s\<\>-]+/, $geneText;
    open INTERACTIONSFILE, ">$tempPath"."additionalinteractions.txt";
    my $i =0;
    while ($i < $#interactionsList)
    {
        my $gene1 = uc($interactionsList[$i]);
        $gene1 =~ tr///;
        my $gene2 = uc($interactionsList[$i + 1]);
        $gene2 =~ tr///;
        print INTERACTIONSFILE $gene1, "\t", $gene2, "\n";
        $i += 2;
    }
    close INTERACTIONSFILE;
}

sub create_job #(jobId)
{
	my $jobId = shift;

	my $depth = param('depth');

	my $bidirectional = param('bidirectional');

	my $layout = param('layout');

	#Commands are separated by semicolons, and run sequentially
	my $commands = "perl runpathgen.pl $jobId $depth $bidirectional $layout;";
	$commands .= "perl makeGraph.pl $jobId;";
	
	my $ipAddress = remote_host();

	open IPFILE, ">>$IPLOGFILE" or print "Could not open Logging File";
	print IPFILE "$jobId\t$ipAddress\n";
	close IPFILE;
		
	my $dbh = DBI->connect("dbi:mysql:database=$DBNAME;host=$DBHOSTNAME","$DBUSERNAME","$DBPASSWORD") or die "Unable to connect to the pathgen database";
	my $sql = "UPDATE $DBJOBTABLE SET created = CURRENT_TIMESTAMP, commands = '$commands', ip = '$ipAddress' WHERE pid = $jobId;";
	my $Update = $dbh->prepare($sql);
	$Update->execute();
	$dbh->disconnect();
}

sub endGenes_textbox #()
{
	my $title = 'Target Genes';
	my $divId = 'divEndGeneFinder';
	my $tableId = 'tbEndGeneFinder';
	my $tbFinderId = 'textEndGeneFinder';
	my $class = 'geneFinderSelected';
	my $blurVar = 'endGeneBlurVar';
	my $posVal = '52%';

	return generic_genefinder_textbox($title,$tbTargetName,$divId,$tableId,$tbFinderId,$class,$blurVar,$posVal);
}

sub generic_genefinder_textbox #(title,tbGenesId,divId,tableId,tbFinderId,class,blurVar,posVal) 
	# title: title for genefinder control
	# tbGenesId: id of textbox where genes to be analyzed by pathgen
	# divId: id of div where AJAX found genes will be put
	# tableId: id of table containing found genes
	# tbFinderId: id of textbox where the user types to find genes
	# class: class name for highlighted found genes
	# blurVar: blur variable name
	# posVal: the horizontal placement of the found genes box (e.g. '20%' or '20px')
	# NOTE: all of these variables are arbitrary, but must be unique between each instantiation
{
	my ($title, $tbGenesId, $divId, $tableId, $tbFinderId, $class, $blurVar, $posVal) = @_;

	return "<table style='float:left;width:41%;position:relative'>
		<tr> 
			<td colspan='3'><strong>$title</strong> <br>(enter gene names in the Gene Finder)</td>
		</tr>
		<tr>
			<td style='width:7em'>Gene Finder:</td><td align='left'><input id='$tbFinderId' type='text' style='width:5em' autocomplete='off'
				onkeydown=\"return geneKeyPressed(event,'$tbFinderId','$tableId','$class','$tbGenesId','$divId')\" 
				onkeyup=\"getGeneInfo(event, this,'$divId','$tableId','$class','$tbGenesId','$tbHiddenTaxa');\"
				onclick=\"$blurVar = 0;getGeneInfo(event, this,'$divId','$tableId','$class','$tbGenesId','$tbHiddenTaxa');\"
				onblur=\"if (typeof $blurVar != 'undefined') hideIfNotBlur('$divId', $blurVar, '$tbFinderId');\"
				onfocus=\"setCursorToEnd(this);\"
				/>
			</td></tr><tr><td></td><td align='left' style='padding-top:0px;'
				onmouseover='$blurVar = 1;' onmouseout='$blurVar = 0;'>
				<div id='outer$divId' class='geneFinderDiv' style='position:fixed;left:$posVal'>
				<span id='$divId' style='display:none'> Finding genes..
				</span>
				</div>
			</td></tr>
		<tr>
			<td align='center' colspan='3'>
			<textarea id='$tbGenesId' name='$tbGenesId' style='float:left;width:100%;z-index:0' rows='$tbRows' cols='' ></textarea></td>
		</tr>
			</table>";
}

sub get_expr_upload #($jobId)
{
	my $jobId = shift;
	my $safe_filename_characters = "a-zA-Z0-9_.-";
	if (param('expressionFile') eq "")
	{return;}
	my $upload_filehandle = upload('expressionFile');
	open OUTEXPR, ">$OUTPUTDIR/job$jobId/expr.dat";
	while (<$upload_filehandle>)
	{
		print OUTEXPR;
	}
	close OUTEXPR;
}

sub get_jobId #()
{
	my $dbh = DBI->connect("dbi:mysql:database=$DBNAME;host=$DBHOSTNAME","$DBUSERNAME","$DBPASSWORD") or die "Unable to connect to the pathgen database";
	my $sql = "INSERT INTO $DBJOBTABLE(created) VALUES(0)";
	my $Insert = $dbh->prepare($sql);
	$Insert->execute();

	#return last insert ID
	my $insertID = $dbh->last_insert_id(undef,undef,undef,undef) or die "Couldn't get last insert ID " . $dbh->errstr();
	return $insertID;
	$dbh->disconnect();
}

sub help_tab #()
{
	my $contents = shift;
	my $helpMessage = shift;
	return "
		<table height='35px' style='float:left;border-collapse:collapse' border-style='none'><tr>
			<td width='26px' style='background-position:bottom left;background-repeat:no-repeat;background-image:url($IMAGEFOLDER/tabLeft.png)'></td>
			<td onmouseover=\"this.innerHTML='$helpMessage'\" onmouseout=\"this.innerHTML='$contents'\" valign='top' style='background-position:bottom center;background-image:url($IMAGEFOLDER/tabMiddle.png);font-size:small;'>$contents</td>
			<td width='26px' style='background-position:bottom right;background-repeat:no-repeat;background-image:url($IMAGEFOLDER/tabRight.png)'></td>
		</tr></table>	
	";
}

sub	print_advanced_settings #()
{
	print "<STYLE>

	#tblAdvancedControls tr
	{
		background-color:#BDA469;
	}

	#tblAdvancedControls tr.alt
	{
		background-color:#CCB98C;
	}	
	</STYLE>";
	print "<a style='cursor:pointer' onclick=\"toggleVisibility('tblAdvancedControls');toggleVisibility('advancedOpen');toggleVisibility('advancedClosed');\"><strong>Advanced Controls </strong></a>";
	print "<span id='advancedOpen' style='display:none'><strong>&lt;</strong></span>";
	print "<span id='advancedClosed'><strong>&gt;</strong></span>";
	print "<table id='tblAdvancedControls' border='solid .5px gray' rules='none' style='display:none'>";
	#print numerical depth selector
	print "<tr class='alt'><td>Depth of Search:</td>";
	print "<td>".popup_menu(-name=>'depth', -values=>[1...15],-default=>'3');
	print "</td></tr>";

	#print bidirectional chooser
	my %labels = (1=>"Use paths in any direction",
		0=>"Only use paths pointing from the start to end genes");

	print "<tr><td>Bidirectionality:</td><td>";

	print radio_group(-name=>'bidirectional',
			-values=>['1','0'],
			-default=>['1'],
			-labels=>\%labels,
			-linebreak=>'true'
		);
	print "</td></tr>";

	#print format chooser
	#see http://www.graphviz.org/
	my %labels = (dot=>"Hierarchical layout (default)",
		neato=>"Statistical multi-dimensial scaling",
		fdp=>"Fruchterman-Reingold heuristic clustering",
		twopi=>"Radial layout",
		circo=>"Circular layout");

	print "<tr class='alt'><td>Graph Format:</td><td>";
	print radio_group(-name=>'layout',
			-values=>['dot','neato','fdp','twopi','circo'],
			-default=>['dot'],
			-labels=>\%labels,
			-linebreak=>'true'
		);
	print "</td></tr>";
	
	#print Microexpression file uploader
	print "<tr><td>Microarray Expression File:</td>";
	print "<td>".filefield(-name=>'expressionFile')." <a href='mxdExample.txt'>example</a></td></tr>";

	#print Microarray expression representation choose
	#print "<tr><td>Microarray Expression Representation:</td>";
	#print "<td>".popup_menu(-name=>'expRep', -values=>['Max','Min','Average'],-default=>'Max'),"</td></tr>";

	#print additional relations textbox
	print "<tr class='alt'><td>Additional Known Relations:</td>";
	print "<td><textarea name='$tbPathsName' style='width:95%;height:2em' rows='1' cols=''></textarea></td></tr>";

	#print include textbox
	print "<tr><td>Include Only These Genes:</td>";
	print "<td><textarea name='$tbPathsName' style='width:95%;height:2em' rows='1' cols=''></textarea></td></tr>";

	#print exclude textbox
	print "<tr class='alt'><td>Exclude These Genes:</td>";
	print "<td><textarea name='$tbPathsName' style='width:95%;height:2em' rows='1' cols=''></textarea></td></tr>";

	#print taxa selector
	print "<tr><td>Select Taxa:</td><td>";
	print taxaTool();
	print "</td></tr>";

	#print goto job tool
	print "<tr class='alt'><td>Go To Job: </td>";
	print "<td><input id='$tbGotoJobName' type='text' maxlength='6' size='6' />
	<input type='button' value='Go To Job' 
		onclick=\"var jobId = document.getElementById('$tbGotoJobName').value; 
			window.location = '$OUTPUTDIR/job' + jobId + '/graph.html';\"/>";
		print "</td></tr>";

	print "</table>";

}

sub print_default_form #()
{
	print "<div id='divGeneInput' style='width:100%;float:left'>";
	print textbox_spacer();
	print "<div style='z-index:3'>";
	print startGenes_textbox();
	print "</div>";
	print textbox_spacer();
	print "<div style='z-index:1'>";
	print endGenes_textbox();
	print "</div>";
	print textbox_spacer();
	print "</div>";
	print "<div id='divSettings' style='width:100%;float:left;padding:5px'>";
	print_advanced_settings();
	print "</div>";
	print submit($btnSubmitName);
	print "<br><a href='/pathgen'>Help</a>";
}

sub print_redirect #(jobId)
{
	my $jobId = shift;
	my $tempPath = "$OUTPUTDIR/job$jobId/graph.html";
	open HTMLFILE, ">$tempPath";
	print HTMLFILE start_html(-title=>'PathGen - Pathway Generation Tool', -style=>{-src=>'../../styles.css'});
	
	print HTMLFILE pathgen->wrapper_start();
	print HTMLFILE "<meta http-equiv='refresh' content='$REFRESHTIME'/>
		This page will be refreshed every $REFRESHTIME seconds until the computation is complete.";
	print HTMLFILE "<p><a href='$PATHTOEMAIL?jobid=$jobId'>Click here</a> to receive an email notification with a link to the results when this job finishes.</p>";
	print HTMLFILE pathgen->wrapper_end();
	print qq(<meta http-equiv=refresh content='$REFRESHTIME; url=$OUTPUTDIR/job$jobId/graph.html'>
		This page will be refreshed every $REFRESHTIME seconds until the computation is complete.
	<p><a href='$PATHTOEMAIL?jobid=$jobId'>Click here</a> to receive an email notification with a link to the results when this job finishes.</p>
	);
}

sub startGenes_textbox #()
{
	my $title = 'Start Genes';
	my $divId = 'divStartGeneFinder';
	my $tableId = 'tbStartGeneFinder';
	my $tbFinderId = 'textStartGeneFinder';
	my $class = 'geneFinderSelected';
	my $blurVar = 'startGeneBlurVar';
	my $posVal = '11%';

	return generic_genefinder_textbox($title,$tbStartName,$divId,$tableId,$tbFinderId,$class,$blurVar,$posVal);
}

sub textbox_spacer #()
{
	return "<div style='float:left;width:6%' ><br/></div>";
}

sub taxaTool#()
{
	return "
		<input type='hidden' id='$tbHiddenTaxa' value=' 9606, 10090,'/>
		<div>
			<input type='checkbox' checked='true' id='cbHum' onclick=\"toggleText('$tbHiddenTaxa',' 9606,');\">Homo sapiens</input><br />
			<input type='checkbox' checked='true' id='cbHum' onclick=\"toggleText('$tbHiddenTaxa',' 10090,');\">Mus musculus</input><br />
			<input type='checkbox' id='cbHum' onclick=\"toggleText('$tbHiddenTaxa',' 7227,');\">Drosophila melanogaster</input><br />
			<input type='checkbox' id='cbHum' onclick=\"toggleText('$tbHiddenTaxa',' ALL');\">All</input><br />
		</div>
	";
}

