#!/usr/bin/env python

# IMPORTANT: the parameter (variable) names used in the web pages should be consistent to those used in Python and R.

import sys, os, cgi #, shelve #, tempfile
#import tools
from cgitools import *

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

my_vars = {'dbs_xref':script_path_url+'/ui/dbs_xref.pih'}
FILENAME = 'DB_ALLOW.txt'

def Exit():
	print cgi_token
	print "<body onload=javascript:window.location.href='%s'></body>" % (my_vars['dbs_xref'])

def getName(s, lower=lower):
	if ':' in s: s = s[:s.index(':')]
	s = s.strip()
	if lower: s = s.lower()
	return unescape(s)


# Retrieve data from user
form = cgi.FieldStorage()

use_file = False
if use_file:
	import fcntl
	colname = escape(form.getvalue('colname').strip())
	if not colname: Exit()
	descript = escape(form.getvalue('descript').strip())

	#lines = open(FILENAME).readlines()
	fd = os.open(FILENAME, os.O_RDWR)
	LOCKFD = fcntl.flock(fd, fcntl.LOCK_EX)
	contents = []
	while True:
		s = os.read(fd, 1000)
		if not s: break
		contents.append(s)
	contents = ''.join(contents)
	contents = contents.split('\n')
	contents = map(getName, contents)
	if colname in contents: Exit()
	os.lseek(fd, 0, 2)
	if contents and contents[-1]: colname = '\n' + colname
	os.write(fd, ' : '.join([colname, descript, username]))
	#os.close(LOCKFD)
	os.close(fd)
else: # use db
	colname = form.getvalue('colname').strip()#.replace('\\','\\\\').replace('"','\\"')
	update_xpf_id = form.getvalue('update_xpf_id')
	descript = form.getvalue('descript').strip()#.replace('\\','\\\\').replace('"','\\"')
	if not colname: Exit()
	exec get_dbstr()
	cur = getCursor()
	import sets
	dblines = sets.Set(map(lambda a:a[0].lower(), inquireDB('SELECT name FROM %s.refdbs ORDER BY name' % db, cursor=cur, fetch=True)))
	if colname.lower() in dblines: Exit()
	uid = inquireDB('SELECT id FROM %s.users WHERE user_name="%s"' % (db, username), cursor=cur, fetch=True)
	uid = uid and uid[0][0]
	inquireDB('INSERT INTO %s.refdbs (user_id, name, update_xpf_id, description) VALUES (%s, "%s", "%s", "%s")' % (db, uid and str(uid) or 'NULL', escSql(colname), update_xpf_id, escSql(descript)), cursor=cur)
	saveEvent(user_id=uid, ev_catcode="addxref", ev_valstr=colname, cur=cur)

Exit()

