#!/tools/bin/python2.5
import simplejson
import cgi
import cgitb
cgitb.enable()
import os
import urllib2
import urllib
import time
import sys

params = os.environ.get("REQUEST_URI").split("pyproxy",1)
criteria = ""
qmarkers = ""
inputchr = ""
inputmarker = ""
# Create instance of FieldStorage 
qform = cgi.FieldStorage() 
listview = 0

# Get data from fields
qcollection = qform.getvalue('qcollection')
quote = "%22"
pplog = open("./pplog", "a")
pplog.write(time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + " " + params[1] + "\n")

if (qcollection == "progenyset"):
	qvsignature = qform.getvalue('qsignature')
	criteria = "{" + quote + "signature" + quote + ":" + quote + qvsignature + quote + "}"

if (qcollection == "markersummary_1108" or qcollection == "markersummary2" or qcollection == "markersummary_0530"):
	qvchr = qform.getvalue('qchr')
	mtquote = "%22"
	#if (qvchr != "mt"):
	#	mtquote = "";
	criteria = "{" + quote + "chromosome" + quote + ":" + quote + qvchr + quote + "}"

#within qcollection call, do an get in strains for each chr/marker and then in strain, at most 100 strains
if (qcollection == "hapcalls" or qcollection == "hapalleles_1108" or qcollection == "hapalleles_0530" or (qcollection.find("hapalleles") != -1)):
	qvchr = qform.getvalue('qchr')
	if (len(qvchr) == 1):
		inputchr = quote + "chr0" + qvchr + quote
	else:
		inputchr = quote + "chr" + qvchr + quote
	inputmarker = qform.getvalue('qmarkers')
	if (inputmarker != None and inputmarker != "ALL" and qvchr == "ALL"):
		inputchr = ""
		#qmarkers - check for chrN:pos1 chrN:pos2 chrN:pos3 ...
		markerssplt = inputmarker.split(" ")
		inputmarker = ""
		chrhash = {}
		for mk in markerssplt:
			chrmk = mk.split(":")
			if (chrhash.get(chrmk[0]) == None):
				inputchr = inputchr + quote + chrmk[0] + quote + ","
			inputmarker = inputmarker + chrmk[1]  + "," 
		inputchr = inputchr[0:len(inputchr)-1]
		inputmarker = inputmarker[0:len(inputmarker)-1]
	elif (inputmarker != None and inputmarker.find("-") != -1):
		#range of markers
		markers = inputmarker.split("-")
		qmarkers = ",%22position%22:{%22%24gt%22:" + markers[0] + "}" + ",%22position%22:{%22%24lt%22:" + markers[1] + "}"
	elif (inputmarker != None and inputmarker.find(" ") != -1):
		#list of markers, discrete range
		listview = 1
		markerssplt = inputmarker.split(" ")
		inputmarker = ""
		for mk in markerssplt:
			inputmarker = inputmarker + mk  + ","
		inputmarker = inputmarker[0:len(inputmarker)-1]
		#qmarkers = ",%22position%22:{%22%24gt%22:" + markers[0] + "}" + ",%22position%22:{%22%24lt%22:" + markers[1] + "}"
	qallele = qform.getvalue('qallele');
	if(qallele != None and qallele != ""):
	    #want to find strains for this allele in this marker
	    if(qallele == "1"):
	        qalleleList="1,11,3";
	    elif(qallele == "2"):
	        qalleleList="2,22,3";
	    criteria = "{%22chromosome%22:" + inputchr  + ",%22position%22:{%22%24in%22:%5B" + inputmarker + "%5D},%22allele%22:{%22%24in%22:%5B" + qalleleList + "%5D}}"
	else:
	    qvstrain = qform.getvalue('qstrains')
	    pplog.write(qvstrain + "\n")
	    stk = qvstrain.strip().split(" ");
	    strains = ""
	    for tk in stk:
		    strains = strains + quote + tk + quote + ","
	    qvstrain = strains[0:len(strains)-1]
	    #qvstrain = urllib.quote(qvstrain)
	    pplog.write(qvstrain + "\n")
	    if (qvchr != "ALL" and (listview == 0)):
        	criteria = "{" + quote + "strain" + quote + ":{%22%24in%22:%5b" + qvstrain + "%5D}" + ",%22chromosome%22:" + inputchr + qmarkers + "}" + "&sort={%22position%22:1}"
		#db.hapcalls.find({chr:'chrmt',strain:{$in:['YPG893', 'YPG990', 'YPG1089', 'YPG1113']}}).sort({'markers':1})  
	    elif (listview != 0 and qvchr == "ALL"):
		#%5b = [ %5D = ]
		    criteria = "{" + quote + "strain" + quote + ":{%22%24in%22:%5B" + qvstrain + "%5D}" + ",%22chromosome%22:{%22%24in%22:%5b" + inputchr + "%5D}" + ",%22position%22:{%22%24in%22:%5b" + inputmarker + "%5D}}" + "&sort={%22position%22:1}"
	    elif (listview != 0):
		    criteria = "{" + quote + "strain" + quote + ":{%22%24in%22:%5b" + qvstrain + "%5D}" + ",%22chromosome%22:" + inputchr  + ",%22position%22:{%22%24in%22:%5b" + inputmarker + "%5D}}" + "&sort={%22position%22:1}" 
	
fields = "{%22chromosome%22:1,%22strain%22:1,%22position%22:1,%22allele%22:1,%22plate%22:1,%22tetrad%22:1}"	
exportVal = qform.getvalue('export')
if(exportVal != None and exportVal == "true"):
	mongooseurl ="http://saskatoon:27080/nvyhapdb/" + qcollection + "/_find?criteria=" + criteria + "&batch_size=1000";
else:
	mongooseurl = "http://saskatoon:27080/nvyhapdb/" + qcollection + "/_find?criteria=" + criteria + "&batch_size=1000"; 
pplog.write("\n" + mongooseurl + "\n")

totalppresp={}
totalppresp['results']=[]

req = urllib2.Request(mongooseurl, None, {
"API_KEY":"952975ec-93c3-44c0-b32a-e68dbafea5ce"})
response = urllib2.urlopen(req)

ppresp = simplejson.loads(response.read())

pplog.write(time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + " " + str(ppresp) + "\n")

while(len(ppresp['results']) > 0):
	for j in range(0, len(ppresp['results'])):
		totalppresp['results'].append(ppresp['results'][j])

	cursorid=ppresp['id']
	if(exportVal != None and exportVal == "true"):
        	mongooseurl ="http://saskatoon:27080/nvyhapdb/" + qcollection + "/_more?id=" + str(cursorid) + "&batch_size=1000";
	else:
        	mongooseurl = "http://saskatoon:27080/nvyhapdb/" + qcollection + "/_more?id=" + str(cursorid) + "&fields=" + fields + "&batch_size=1000";

	req = urllib2.Request(mongooseurl, None, {"API_KEY":"952975ec-93c3-44c0-b32a-e68dbafea5ce"})
	response = urllib2.urlopen(req)
	ppresp = simplejson.loads(response.read())	


header="Content-type: text/html"
header2="";

if(exportVal != None and exportVal == "true"):
	header="Content-type: text/csv; Content-Disposition: attachment; filename='progenydetails.csv'\n";
	pplog.write("results length: " + str(len(totalppresp['results'])));
	resultString="strain,chromosome,position,barcode,plate,tetrad,spore,score_p1,score_p2,supporting_reads,allele,";
	resultString=resultString+"perfect_p1_reads,perfect_p2_reads,total_perfect_reads,allele_call_2,yseq,cross\n";
	if(len(totalppresp['results']) > 0):
		for i in range (0, len(totalppresp['results'])):
			detailObj=totalppresp['results'][i];
			resultString=resultString + str(detailObj['strain']) +"," + str(detailObj['chromosome']) + "," + str(detailObj['position']) + ",";
			resultString=resultString + detailObj['barcode'] + "," + detailObj['plate'] + "," + str(detailObj['tetrad']) + "," + str(detailObj['spore']) + ",";
			resultString= resultString + str(detailObj['score_p1']) + "," + str(detailObj['score_p2']) + "," + str(detailObj['supporting_reads']) + ",";
			resultString=resultString + str(detailObj['allele']) + "," + str(detailObj['perfect_p1_reads']) + "," + str(detailObj['perfect_p2_reads']) + ",";
			resultString=resultString + str(detailObj['total_perfect_reads']) + "," + str(detailObj['allele_call_2']) + ",";
			resultString=resultString + str(detailObj['yseq']) + "," + str(detailObj['cross']) +  "\n"; 	

	pplog.write("done exporting: " + resultString);	
	finalresp=resultString
	pplog.close()

	print header
	print
	print finalresp
else:
	pplog.close();
	print header
	print
	print simplejson.dumps(totalppresp)

