#!/usr/bin/env python

import os, sys, time, cPickle, traceback, cStringIO
from db_vars import *
from rpy import r, set_rpy_output

error_msg = []

def myout(*a, **b): pass
set_rpy_output(myout)


def runR_rpy():#req_type, req_id, user_params, R_code_dir):
	#from rpy import r, set_rpy_output
	#set_rpy_output(myout)

	req_type, req_id, user_params, R_code_dir = cPickle.loads( sys.stdin.read() )
	
	rlt = None
	error_msg = []
	try:
		lcwd = os.getcwd()
		os.chdir(R_code_dir)
		#r("rm(list=ls())")
		if req_type in (TYPE_NORM_ANALYSIS, TYPE_LINEAR_DUAL):
			r.assign("user.params", user_params)
			rlt =  r("source('LinearDual.R')")
		elif req_type == TYPE_LINEAR_AFFY:
			r.assign('user.params', user_params)
			rlt = r("source('LinearAffy.R')")
		elif req_type == TYPE_NORMPCA:
			rlt = r("source('normPCA.R')")
			for k,v in user_params.items(): r.assign(k, v)
			rlt = r("fullNormalize(intensity_file, output_dir, chart_dir, plotPCA=plotPCA, plotAF=plotAF, plotAFD=plotAFD, plotHK=plotHK, sig_level=sig_level, ave_num=ave_num)") 
		else:
			rlt = None # do other analysis
		os.chdir(lcwd)
	except: 
		os.chdir(lcwd)
		error_msg.append('Error happened in R: <p>') #might caused by wrong parameters from user.')
		cfile = cStringIO.StringIO()
		traceback.print_exc(None,cfile)
		value = cfile.getvalue()

		value = value.replace('\n', '<br>')
		value = value.replace('"', '\'\'')
		err_tk = 'error: '
		err_st = value.find(err_tk)
		if err_st >= 0: value = value[err_st+len(err_tk):]
		error_msg.append(value)

	if error_msg:
		error_msg.append('''<p><spacer type='vertical' size=250>
<table><tr><td height=120></td></table>
<hr width=50% align=center>
<center>
<font size=-1>
	Please report bugs to <a href=mailto:xxia@skcc.org>Xiao-Qin Xia</a><br>For questions about analysis, please contact <a href=mailto:ywang@skcc.org>Yipeng Wang</a><br><a href=http://www.skcc.org>Sidney Kimmel Cancer Center</a></font>
</center>
''')
		msg = ' '.join(error_msg)
		req_state = STATE_ERROR
		sql_update = 'UPDATE requests SET req_state=%d, error_msg="%s" WHERE req_id=%d' % (req_state, msg, req_id)
	else: 
		req_state = STATE_SOLVED
		date_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
		sql_update = 'UPDATE requests SET req_state=%d, solve_time="%s" WHERE req_id=%d' % (req_state, date_time, req_id)
	#n = inquireDB(sql_update)
	
	#os.write( sys.stdout.fileno(), cPickle.dumps( (rlt, sql_update) ) )
	sys.stdout.write( cPickle.dumps( (rlt, sql_update) ) )
	sys.stdout.close()


if __name__ == '__main__':
	try:	
		runR_rpy()
	except:
		cfile = cStringIO.StringIO()
		traceback.print_exc(None,cfile)
		value = cfile.getvalue()
		value = value.replace('\n', '<br>')
		value = value.replace('"', '\'\'')
		os.write(sys.stdout.fileno(), cPickle.dumps( ('Nothing done', value) ) )
	
