#!/usr/bin/env python

import os, sys, time, cPickle, traceback, cStringIO, re
from db_vars import *
from tools import esc_sql_1, bug_report_fmt

#from toolfunc import *


error_msg = []
#R_halt_str = re.compile(r'\nExecution halted\n*\Z')
error_head = '<h1>Error Message</h1><br><p>'

PIPE_CMD = 'python filldbs.py --ACCEPT_DATA_FROM_PIPE'

def htmlStr(s): return s.replace('\n','<br>').replace('"', "''")

def runPipe():
	#req_type, req_id, user_params, R_code_dir = cPickle.loads( sys.stdin.read() )
	req_type, req_id, user_params = cPickle.loads( sys.stdin.read() )
	#prj_file = user_params['prj_file']
	#src_dir = user_params['src_dir']
	#user_name = user_params['user_name']
	#fill_type = 'By file'
	#user_list = cPickle.dumps((fill_type, (prj_file, src_dir, user_name))) #"user.params <- " + GetStr(user_params) + ';\n'

	cwd = os.getcwd()
	os.chdir(os.path.split(os.path.abspath(__file__))[0])
	rlt = None
	error_msg = []
	try: 
		Rin, Rout = os.popen4(PIPE_CMD)
		os.write(Rin.fileno(), cPickle.dumps(user_params))
		Rin.close()
		rlt = Rout.read()
		Rout.close()
		os.chdir(cwd)
	except: 
		os.chdir(cwd)
		#rlt = None
		if rlt: 
			error_msg.extend(htmlStr(rlt))
			rlt = None
		error_msg.append('<p>Error happened when filling data to database: <p>') #might caused by wrong parameters from user.')
		cfile = cStringIO.StringIO()
		traceback.print_exc(None,cfile)
		value = htmlStr(cfile.getvalue())

		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 rlt and rlt[-14:] == 'Error ocurred!': 
	#if not rlt or rlt[-13:] != 'Job was done.': 
	if not rlt or '\n\nJob was done.' not in rlt: # sometimes there other warning information after 'Job was done.' under windows
		error_msg.append(htmlStr(rlt))
			
	date_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
	if error_msg:
		error_msg.insert(0, error_head)
		error_msg.append(bug_report_fmt)
		msg = esc_sql_1.sub(r'\\\1', ' '.join(error_msg))
		req_state = STATE_ERROR
		sql_update = 'UPDATE requests SET req_state=%d, error_msg="%s", solve_time="%s" WHERE req_id=%d' % (req_state, msg, date_time, req_id)
	else: 
		req_state = STATE_SOLVED
		if rlt: sql_update = 'UPDATE requests SET req_state=%d, error_msg="%s", solve_time="%s" WHERE req_id=%d' % (req_state, esc_sql_1.sub(r'\\\1', htmlStr(rlt)), date_time, req_id)
		else: sql_update = 'UPDATE requests SET req_state=%d, solve_time="%s" WHERE req_id=%d' % (req_state, date_time, req_id)
	sys.stdout.write( cPickle.dumps( (rlt, sql_update) ) )
	sys.stdout.close()


if __name__ == '__main__':
	try:	
		runPipe()
	except:
		cfile = cStringIO.StringIO()
		traceback.print_exc(None,cfile)
		value = htmlStr(cfile.getvalue())
		os.write(sys.stdout.fileno(), cPickle.dumps( ('Nothing done', value) ) )
	
