#!/usr/bin/env python

import sys, types
#from deldbs import *

from tools import *
from cgitools import isOnline, script_path_url, js_dir, username, cgi_token_xml

# get default db name
exec get_dbstr()

# need dbnm, tbnm, rec_id, colname, value, type, dyn from pih_vars

print cgi_token_xml

def exitInfo(s):
	print '<data>%s</data>' % s
	sys.exit(0)

def failed(): exitInfo('failed')

def mapOpt(opt, sel=''):
	if type(opt) in (types.TupleType, types.ListType): 
		ov, ot = opt[0], opt[1] # value, text
		if len(opt)>=3: selstr = opt[2]
		else: selstr = ov==sel and ' selected' or ''
	else: 
		ov = ot = opt
		selstr = ov==sel and ' selected' or ''
	return '<option value="%s"%s>%s</option>' % (ov, selstr, ot)

def getOptions(opts, sel=''):
	return ''.join(map(mapOpt, opts) )

def ProbeType_no_use(s):
	tp = 'tsv'
	if 'Probe Set ID' in s and 'GeneChip Array' in s: return 'affy'
	return tp

if not isOnline(): failed() #exitInfo('Please long on')

# accept pih_vars from #ui
pih_vars = eval(unescape(os.getenv('QUERY_STRING')))

dbnm = pih_vars.get('db', db)
rec = pih_vars.get('rec', None) # rec should be an int
if type(rec) is not type(3): failed() #exitInfo('failed')

# check privilege permission
cur = getCursor()
fn = inquireDB('SELECT f.location, f.name FROM %s.filexref x, %s.fileinfo f WHERE x.tb_id=%d AND x.tbname="platform" AND x.file_id=f.id' % (dbnm, dbnm, rec), cursor=cur, fetch=True)
if not fn: failed() #exitInfo('failed')
fn = os.path.join(fn[0][0], fn[0][1])

try:
	pf_type, annotation_ln = ProbeFileType(fn)
	f = open(fn)
	for i in range(annotation_ln): f.readline()
	head = f.readline().strip()
	
	#if ProbeType(head) == 'tsv':
	#	head = head.split('\t')
	#else:
	#	if head[0] == head[-1] == '"': 
	#		delim = '"'
	#		head = head[1:-1]
	#	else: delim = ''
	#	if ("%s,%s" % (delim, delim)) in head: sep = "%s,%s" % (delim, delim)
	#	else: sep = '\t'
	#	head = head.split(sep)

	if head[0] == head[-1] == '"' and '","' in head: head = head[1:-1].split('","')
	else: head = head.split('\t')

	#.split('\t')
	head = filter(lambda b:b, map(lambda a:rmDelim(a).strip(), head))
	#exitInfo(getOptions(head)) #!!!!!!!! cannot exit from "try", this will lead to "except"
except: failed() #exitInfo('failed')

exitInfo(str(head))
#exitInfo(getOptions(head))
