#!/usr/bin/env python

import os, sys
from cgitools import isOnline, cgi_token, exitWithInfo, decodeStr, getCursor, inquireDB, data_subdirs, prepareDirnames

#print   'Content-type:   text/plain   name="test_name"\n'
#print   'Content-Disposition:   inline; filename="obj.Rdata"\n\n'  

#print "Content-Type:application/octet-stream\n"
#print "Content-Disposition:attachment;filename='test_name'\n\n"


#print "Content-Disposition: attachment;filename=test_file\n"
#print "Content-Transfer-Encoding: binary\n"
#print "Accept-Ranges: bytes\n"
#print "Content-Length: %ld\n" % os.stat(fn).st_size
#print "Connection: close\n"
#print "Content-type: application/octet-stream\n"
#print "\n");  

# need a comma after "print" to prevent extra line char - '\n'
#print "Content-Type:application/x-download\n",
#print "Content-Disposition:attachment;filename=%s\n\n" % fn,
#print open(fn, 'rb').read(), # this will append a line char anyway

if not isOnline(): exitWithInfo('Logon first please.')

goback = '<p><input type="button" value="Go back" onClick="javascript:history.go(-1)"/>'

request_page = os.getenv('QUERY_STRING')
if not request_page: #is None: 
	request_page = os.getenv('PATH_INFO')
	if request_page and len(request_page)>1: request_page = request_page[1:] # remove the leading slash '/'
	else: exitWithInfo('No database name and record number offered!' + goback)

cur_db, rec_id = eval(decodeStr(request_page))

cursor = getCursor()
pfname = inquireDB('SELECT name FROM %s.platform WHERE id=%d' % (cur_db, rec_id), cursor=cursor, fetch=True)
if not pfname: exitWithInfo('No such a platform!' + goback)
pfname = pfname[0][0]
# read probe information from database
sql = '''
SELECT idx, block_row, block_col, row, col, unique_id, gene_title
FROM %s.probe
WHERE platform_id=%d
ORDER BY idx
''' % (cur_db, rec_id)
infos = list(inquireDB(sql, cursor=cursor, fetch=True))
cn = max(map(lambda a:a[2], infos))

dir_name = data_subdirs['gal'].get('name_full', '')
if not dir_name:
	try: prepareDirnames()
	except: 
		exitWithInfo('Failed to prepare Dirnames!' + goback)
		sys.exit(0)
	dir_name = data_subdirs['gal'].get('name_full','')
obj = os.path.join(dir_name, pfname + '.GAL')
if os.path.exists(obj): 
	pass # or exit
fp = open(obj, 'w')

print >>fp, 'ATF\t1.0\n1\t5\nType=GenePix Array List v1.0\nBlock\tRow\tColumn\tID\tName'
for idx, br, bc, row, col, id, name in infos: print >>fp, '%d\t%d\t%d\t%s\t%s' % ( (br-1)*cn+bc, row, col, id, name)
fp.close()
exitWithInfo('Done.' + goback)

