#!/usr/bin/env python

# IMPORTANT: the parameter (variable) names used in the web pages should be consistent to those used in Python and R.
# the above line is not need now, since a name map is used.

import sys, os #, MySQLdb, cPickle #, tempfile

import cgitb; cgitb.enable(display=0, logdir='/tmp')

from cgitools import *
from tools import decodeStr

#home_dir = '/home/xxia/public_html' # user data will based on this dir
#users_relative_dir = "users"
#users_dir = os.path.join(home_dir, users_relative_dir)
#R_code_dir = 'R_code' # under cgi-bin

#chart_infos = {'Final.Chart':('Final_Results_Plot.png', 'Final chart'), 
#	'Array.Image.Plot':('Array_Image_Plot.png', 'Array image plot'), 
#	'M.A.Plot':('PrintTip_Plot_PrintTip_Norm.png', 'M-A plot'), 
#	'M.Scale.Plot':('M_Scale_Plot.png','M-scale plot'), 
#	'Box.Plot':('Box_Plot_Scale_Norm.png','Box plot')
#	} # the value is (file_name, info_to_be_displayed) 

# in R:
#	Final.Chart.Title = "Final_Results_Plot",
#	Scale.Chart.Title = "Box_Plot_Scale_Norm.png",
#	Array.Chart.Title = "imageplot.slide.",
#	Printtip.Chart.Title = 'printtiploessplot.slides.',
#	Density.Chart.Title.bef = 'densityplot.before.betweenarray.normalization.png',
#	Density.Chart.Title.abs = "densityplot.after.background.subtraction.png",
#	Density.Chart.Title.awn = "densityplot.after.withinarray.normalization.png",
#	Density.Chart.Title.abn = "densityplot.after.betweenarray.normalization.png",
#	MA.Chart.Title = 'plotMA.slides.',
#	Location.Chart.Title = 'plot.CGH.two.samples',


# set mask for file
os.umask(6)
reqs = os.getenv('PATH_INFO')
if reqs: 
	req_id = decodeStr(reqs[1:])
	#reqs = decodeStr(reqs[1:])
	#reqs = reqs.split('/')
	#req_id = reqs[0]
	#if len(reqs) > 1: req_pic = reqs[1]
	#else: req_pic = None
else: 
	print cgi_token
	sys.exit(0)

error_msg = []

#exec open('db').read()
#connection = MySQLdb.connect(host=host, db=db, port=port, user=user, passwd=passwd)
#cursor = connection.cursor()
##sql_statement = 'SELECT id FROM users WHERE user_name="%s"' % username
##n = cursor.execute(sql_statement)
##user_id = cursor.fetchone()[0]
##sql_statement = 'SELECT req_state, req_info, error_msg, category FROM requests WHERE user_id=%d and req_name="%s"' % (user_id, req_name)

#sql_statement = 'SELECT req_state, req_info, error_msg, category FROM requests WHERE req_id="%s"' % req_id
sql_statement = 'SELECT requests.req_state, requests.req_info, requests.error_msg, requests.category FROM requests, users WHERE users.user_name="%s" and users.id=requests.user_id and requests.req_name="%s"' % (username, req_id)

#n = cursor.execute(sql_statement)

#req_state, req_info, error_info, category = cursor.fetchone()
req_state, req_info, error_info, category = inquireDB(sql_statement, fetch=True)[0]
import cPickle
req_info = cPickle.loads(req_info)

#cursor.close()
#connection.close()

print cgi_token

if req_state == STATE_ERROR:
	print error_info.replace('\n', '<p>')
	sys.exit(0)

print "<h1><center>Results of analysis</center></h1>"
print "<body bgcolor='white'>\n"

if error_msg:
	print "<br>".join(error_msg),"<br>"
	sys.exit(0)
	
#subdirs = getRequestDirnames(req_name)

if 0: #category == TYPE_NORM_ANALYSIS:
	result_file = path2url(os.path.join(req_info['result.data.dir'], os.path.basename(req_info['result.data.file'])))
	graph_dir = req_info['chart.dir']
	chart_names = chart_infos.keys()
	#print '<p>', chart_names, '<p>'
	chart_file_names = [chart_infos[k][0] for k in chart_names]
	#print '<p>', chart_file_names
	chart_dirs = dict(zip(chart_names, [os.path.join(graph_dir, k) for k in chart_file_names]))
	chart_urls = dict(zip(chart_names, map(path2url, chart_dirs.values())))
	print "<p>Please view (or download) the result <a href="+result_file+">Here</a>"
	chart_title = 1
	for k,v in chart_urls.items():
		#print '<br>', k,'\t', req_info.get(k, None), '\t', chart_dirs[k], '\t', os.path.exists(chart_dirs[k])
		if req_info.get(k, None) and os.path.exists(chart_dirs[k]):
			if chart_title:
				chart_title = 0
				print "<p><center>Resulted charts</center><br>"
			print "<p>", chart_infos[k][1], ":<br><img src="+v+">"
	print '<p>'
	#for k, v in req_info.items(): print '<br>', k, '\t', v
else: # different result display
	pass
	
#import re
#from Crypto.Cipher import RC5
#from base64 import encodestring
##from binascii import b2a_hex
#rc5 = RC5.new('fetch', RC5.MODE_ECB)
#
#def encodePath(file_path):
#	ln_add = 8 - len(file_path) % 8
#	file_path = ln_add and 'X'*ln_add+file_path or file_path
#	file_path = encodestring(rc5.encrypt(file_path)+str(ln_add))#[:-1]
#	file_path = re.sub('/', '//', file_path)
#	file_path = re.sub('\s', lambda m:'/'+ hex(ord(m.group(0)))[2:].zfill(2), file_path)
from tools import encodeStr

#import zipfile
output_zip = req_id+'_outputs.zip'
files_excluded = ['Rplots.ps']

def isEmptyDir(path):
	if not os.path.isdir(path): return False
	names = os.listdir(path)
	if not names: return True
	cwd = os.getcwd()
	os.chdir(path)
	for k in names:
		if os.path.isfile(k): return False
		elif not isEmptyDir(k): return False
	return True

def zipPath(zip_file, path):
	if os.path.isdir(path):
		names = os.listdir(path)
		if names:
			cwd = os.getcwd()
			os.chdir(path)
			for k in names: 
				if os.path.isfile(k): 
					if k not in files_excluded: zip_file.write(k)
				else: zipPath(zip_file, k)
			os.chdir(cwd)
	else: # should be a regular file
		if path not in files_excluded: zip_file.write(path)
	
def outputZip(path):
	output_name = os.path.join(path, output_zip)
	if os.path.exists(output_name): return
	if isEmptyDir(path): return
	names = os.listdir(path)
	import zipfile
	zip_file = zipfile.ZipFile(output_name, 'w', zipfile.ZIP_DEFLATED)
	cwd = os.getcwd()
	os.chdir(path)
	for k in names: zipPath(zip_file, k)
	zip_file.close()


if category == TYPE_NORM_ANALYSIS or category==TYPE_LINEAR_DUAL or category==TYPE_LINEAR_AFFY:
	if category == TYPE_NORM_ANALYSIS or category==TYPE_LINEAR_DUAL:
		chart_infos = {
			'Final.Chart':{'files':[], 'token':'Final_Results_Plot', 'comment':'Results plot'},  
			'Scale.Chart':{'token':'Box_Plot_Scale_Norm', 'comment':'Box plot'}, 
			'Array.Chart':{'token':'imageplot.slide', 'comment':'Array image plot'}, 
			'Printtip.Chart':{'token':'printtiploessplot.slides', 'comment':'Printtiploess plot'}, 
			'Density.Chart':{'token':'densityplot', 'comment':'Density plot'}, 
			'MA.Chart':{'token':'plotMA.slides', 'comment':'MA plot'}, 
			'Location.Chart':{'token':'plot.CGH.two.samples', 'comment':'Two-Sample CGH plot'} 
			}  # {'files':[], 'token':'', 'comment':''}
		chart_names = chart_infos.keys()
		chart_names.remove('Final.Chart')
		chart_names.sort()
		chart_names.insert(0, 'Final.Chart')
	else: # must be TYPE_LINEAR_AFFY
		chart_infos = {
			'Final.Chart':{'files':[], 'token':'affy.result.chart', 'comment':'Results plot'},  
			'Array.Chart':{'token':'affy.image', 'comment':'Array image plot'}, 
			'Hist.Chart':{'token':'affy.hist', 'comment':'Histogram plot'}, 
			'MAplot.Chart':{'token':'affy.MAplot', 'comment':'MA plot'}, 
			'RNAdeg.Chart':{'token':'affy.RNAdeg', 'comment':'RNA degradation plot'}, 
			'Boxplot.Chart':{'token':'affy.boxplot', 'comment':'Box plot'}, 
			'CGH.Chart':{'token':'affy.CGH.plot', 'comment':'CGH plot'} 
			}  # {'files':[], 'token':'', 'comment':''}
		chart_names = chart_infos.keys()
		chart_names.remove('Final.Chart')
		chart_names.sort()
		chart_names.insert(0, 'Final.Chart')
		

	result_norm_data = "output.normalized.data.txt"
	result_analyzed_data = "output.analyzed.data"
	
	result_dir = req_info['result.data.dir']
	if not os.path.exists(result_dir): result_dir = os.path.join(users_dir, username, relative_result_dir, req_id) # for old requests
	filenames = os.listdir(result_dir)
	filenames.sort()
	name_start = 0
	if filenames and (filenames[0].find(req_id)==0): # for new reqs
		result_norm_data = req_id+'_'+result_norm_data
		result_analyzed_data = req_id+'_'+result_analyzed_data
		name_start = len(req_id+'_')
	
	print "<p><a name = 'RESULT_TOP'></a>"
	outputZip(result_dir)
	zip_name = os.path.join(result_dir, output_zip)
	if os.path.exists(zip_name): print "Please download <a href="+path2url(zip_name)+">the result package</a> (%s bytes)" % os.stat(zip_name).st_size,"- a zip file including all result files."

	if result_norm_data in filenames:
		print "<p>Please view (or download) the normalized data <a href="+path2url(os.path.join(result_dir, result_norm_data))+">Here.</a>"
	
	filenames = filter(lambda a:(result_analyzed_data in a), filenames) #[a for a in filenames if (result_analyzed_data in a)]
	if filenames:
		if len(filenames) == 1:
			print "<p><a name = 'RESULT_TOP'></a>Please view (or download) the result data <a href="+path2url(os.path.join(result_dir, filenames[0]))+">Here.</a>"
		else:
			print "<p><a name = 'RESULT_TOP'></a>Please view (or download) the result data:"
			for fn in filenames:
				full_fn = os.path.join(result_dir, fn)
				print "<br><a href="+path2url(full_fn)+">"+fn+"</a>"
	#result_data_file = "output.analyzed.data.txt"
	#result_file = os.path.join(req_info['result.data.dir'], result_data_file)
	#result_file_url = path2url(result_file)
	#print "<p><a name = 'RESULT_TOP'></a>Please view (or download) the result <a href="+result_file_url+">Here.</a>"
	
	graph_dir = req_info['chart.dir']
	if not os.path.exists(graph_dir): graph_dir = os.path.join(result_dir, relative_chart_dir) # for old requests
	filenames = os.listdir(graph_dir)
	filenames.sort()
	if filenames:
		print '<p><table ><tr><th><b>Charts:</b></th><tr><td><ul>'
		for k in chart_names: #k,v in chart_infos.items():
			v = chart_infos[k]
			v['files'] = filter(lambda a:(v['token'] in a[name_start:]), filenames)
			if v['files']: print '<li><a href=#%s>' % k.replace('.','_'), v['comment'], '</a>'
		print '</ul></td></table>'

		print '<p><ul>'
		for k in chart_names: #k,v in chart_infos.items():
			v = chart_infos[k]
			if v['files']:
				print '<li><font size=+1><b><a name=%s></a>' % k.replace('.', '_'), v['comment'], ' <a href=#RESULT_TOP>(return TOP)</a></b></font>'
				chart_urls = zip(map(lambda a:path2url(os.path.join(graph_dir,a)), v['files']), v['files'])
				print '<br><table>', reduce(lambda a,b:a+('<tr><td align=center><img src="%s"></td><tr><td align=center>%s</td>' % b), chart_urls, ''), '</table>'
		print '</ul>'
		
	'''
	chart_names = chart_infos.keys()
	#print '<p>', chart_names, '<p>'
	chart_file_names = [chart_infos[k][0] for k in chart_names]
	#print '<p>', chart_file_names
	chart_dirs = dict(zip(chart_names, [os.path.join(graph_dir, k) for k in chart_file_names]))
	chart_urls = dict(zip(chart_names, map(path2url, chart_dirs.values())))
	#print result_file,'<br>'
	print "<p>Please view (or download) the result <a href="+result_file_url+">Here</a>"
	#print "<p>Please view (or download) the result <a href="+script_path_url+'/outputtxt/'+encodeStr(result_file)+">Here</a>"
	chart_title = 1
	for k,v in chart_dirs.items():
		#print '<br>', k,'\t', req_info.get(k, None), '\t', chart_dirs[k], '\t', os.path.exists(chart_dirs[k])
		if req_info.get(k, None) and os.path.exists(v):
			if chart_title:
				chart_title = 0
				print "<p><center>Resulted charts</center><br>"
			print "<p>%s:<br><img src=%s>" % (chart_infos[k][1], chart_urls[k])
			#print "<p>%s:<br><img src=%s/image/%s>" % (chart_infos[k][1], script_path_url, encodeStr(v))
	print '<p>'
	#for k, v in req_info.items(): print '<br>', k, '\t', v
	'''
elif category == TYPE_NORMPCA:
	chart_infos = {'Angle_freq_dist_num.png':{'comment':'Angle frequency distribution'}, 
		'Angle_freq.png':{'comment':'Angle frequency'}, 
		'House_keeping.png':{'comment':'House keeping genes'}, 
		'R1_R2.png':{'comment':'R1 versus R2'} 
		} # the value is (file_name, info_to_be_displayed) 
	result_dir = req_info['output_dir']
	if not os.path.exists(result_dir): result_dir = os.path.join(users_dir, username, relative_result_dir, req_id) # for old requests
	result_file = os.path.join(result_dir, 'normalized_by_pca.txt')
	result_file_url = path2url(result_file)
	graph_dir = req_info['chart_dir']
	if not os.path.exists(graph_dir): graph_dir = os.path.join(result_dir, relative_chart_dir) # for old requests
	for k in chart_infos.keys(): 
		full_name = os.path.join(graph_dir, k)
		chart_infos[k]['full'] = full_name
		if os.path.exists(full_name): chart_infos[k]['exist'] = True
		else: chart_infos[k]['exist'] = False
		
	print "<p><a name = 'RESULT_TOP'></a>"
	outputZip(result_dir)
	zip_name = os.path.join(result_dir, output_zip)
	if os.path.exists(zip_name): print "Please download <a href="+path2url(zip_name)+">the result package</a> (%s bytes)" % os.stat(zip_name).st_size,"- a zip file including all result files."
	
	print "<p>Please view (or download) the result <a href="+result_file_url+">Here.</a>"
	print '<p><table><tr><th><b>Charts:</b></th><tr><td><ul>'
	for k,v in chart_infos.items(): 
		if v['exist']: print '<li><a href=#%s>' % k.replace('.','_'), v['comment'], '</a>'
	print '</ul></td></table><p><ul>'
	for k,v in chart_infos.items():
		if v['exist']:
			print '<li><font size=+1><b><a name=%s></a>' % k.replace('.', '_'), v['comment'], ' <a href=#RESULT_TOP>(return TOP)</a></b></font>'
			print '<br><table><tr><td align=center><img src="%s"></td><tr><td align=center>%s</td>' % (path2url(v['full']), k), '</table>'
	print '</ul>'
else: # different result display
	pass

print "</body>"


