#!/usr/bin/env python

import sys, os, cgi, types
from cgitools import *


if not isOnline(): sys.exit(0)

def addCols(output=sys.stdout, inputs=[], cols=[], by_index=False, sep='\t'):
	n = len(inputs)
	rng = range(n)
	#heads = map(lambda a:a.readline().replace('\n','').replace('\r','').split(sep), inputs)
	heads_raw = map(lambda a:a.readline(), inputs)
	heads = map(lambda a:a.replace('\n','').replace('\r','').split(sep), heads_raw)
	if by_index: indice = map(lambda i:(not cols[i]) and range(len(heads[i])) or [int(cln)-1 for cln in cols[i]], rng)
	else: indice = map(lambda i:(not cols[i]) and range(len(heads[i])) or [heads[i].index(cln) for cln in cols[i] if cln in heads[i]], rng)
	blanks = map(lambda a:sep*(len(a)-1), indice)

	if not indice: return
	#map(lambda a:a.seek(0,0), inputs)
	map(lambda a:a[0].seek(-len(a[1]),1), zip(inputs, heads_raw))
	has_data = [True] *n 
	
	row_no = 0
	while 1:
		#line = []
		if not row_no: # first row
			line = ['ID'] + map(lambda a:'ch%d.Intensity' % (a+1), rng)
			print >> output, sep.join(line)
			row_no = row_no + 1
			map(lambda i:inputs[i].readline(), rng)
			continue
		else: 
			line = [str(row_no)]
			row_no = row_no + 1
		for i in rng:
			if has_data[i]:
				ln = inputs[i].readline()
				if not ln: has_data[i] = False
				ln = ln.replace('\n','').replace('\r','')
				if not ln: ln = blanks[i]
				else:
					ln = ln.split(sep)
					ln = sep.join([ln[j] for j in indice[i]])
			else: ln = blanks[i]
			line.append(ln)
		if not filter(None, has_data): break
		print >> output, sep.join(line)
			
def addColsMain(args=None, sep='\t'):
	output = fn = None
	inputs = []
	inputs_col = []
	if args is None: args = sys.argv[1:]
	n = len(args)
	used = [False]*n
	skip_head = False
	by_index = False
	for i in range(n):
		if used[i]: continue
		used[i] = True
		arg = args[i]
		head = arg[:2]
		if arg == '--skip-head':
			skip_head = True
		elif arg == '--by-index':
			by_index = True
		elif not output and head == '-o':
			output = arg[2:]
			if not output:
				output = args[i+1]
				used[i+1] = True
		elif head == '-i':
			fn = arg[2:]
			if not fn:
				fn = args[i+1]
				used[i+1] = True
			#if not inputs_dict.has_key(fn):
			inputs.append(fn)
			inputs_col.append([])
		else:
			if fn:
				inputs_col[-1].append(arg)
			
	if not inputs: return None 
	finputs = map(lambda a:file(a,'r'), inputs)
	if skip_head: # skip annotation lines
		for fp in finputs:
			while True:
				line = fp.readline()
				if not line: break
				if not line.strip(): continue
				if line.startswith('#'): continue
				fp.seek(-len(line), 1)
				break
			
	foutput = output and file(output,'w') or sys.stdout
	cols = inputs_col #map(lambda a:inputs_dict[a], inputs)
			
	addCols(output=foutput, inputs=finputs, cols=cols, by_index=by_index, sep=sep)
	
	map(lambda a:a.close(), finputs)
	foutput.close()
	return True

def Main():
	msg = []
	# Retrieve data from user
	form = cgi.FieldStorage()

	sortxy = form.has_key('sortxy')
	ch1 = form.getvalue('grps_1', [])
	if type(ch1) is not types.ListType: ch1 = [ch1]
	ch2 = form.getvalue('grps_2', [])
	if type(ch2) is not types.ListType: ch2 = [ch2]
	new_names = filter(lambda a:a, map(str.strip, form.getvalue('new_name', '').split('\n')))
	if not (len(ch1) == len(ch2) == len(new_names)): 
		msg.append('Different number of files in the two channels or the names for new files')
		exitInfo(msg)
	elif not len(ch1): 
		msg.append('Some required items are empty')
		exitInfo(msg)

	dir_name = data_subdirs['intensity'].get('name_full','')
	for src1, src2, obj in zip(ch1, ch2, new_names):
		fobj = os.path.join(dir_name, obj)
		if os.path.exists(fobj):
			msg.append('Error: "%s" exists, didn\'t converted to it. Please remove it or use a different name for the new file.' % obj)
			continue
		try:
			rlt = addColsMain(args=['--skip-head', '-o', fobj, '-i', os.path.join(dir_name, src1), 'SIGNAL', '-i', os.path.join(dir_name, src2), 'SIGNAL'])
			if rlt: msg.append('convert "%s" and "%s" to "%s" successfully.' % (src1, src2, obj))
			else: msg.append('Didn\'t convert "%s" and "%s" to "%s".' % (src1, src2, obj))
		except:
			raise
			if os.path.exists(fobj): os.unlink(fobj)
			msg.append('Error occured when convert "%s" and "%s" to "%s".' % (src1, src2, obj))
	exitInfo(msg)

def exitInfo(msg):
	print cgi_token
	print '<br>'.join(msg)
	print '''<p><input type="button" value="Go back" onClick="JavaScript:window.location.href='%s'"/>''' % (script_path_url+'/ui/dbs_mkintensity.pih')
	#print '<p>'
	##for k,v in form.items(): print '<br>', k , ' : ', v
	#for k in form.keys(): print '<br>', k , ' : ', form.getvalue(k)
	#print '<p>', form
	sys.exit(0)
		

if __name__ == '__main__': 
	Main()

