#!/usr/bin/env python

import sys, os, cgi, time, types, re
from cgitools import *
#cgi_token = "Content-type:text/html\n\n"
#error_info = []

data_set = {'user_id':{'required':1, 'to_upper':0}, 'password':{'required':1, 'to_encrypt':'md5'}, 'password_confirm':{'required':1, 'to_encrypt':'md5'}, 'first_name':{'required':1}, 'last_name':{'required':1}, 'company':{}, 'street':{}, 'city':{}, 'state':{}, 'zip':{}, 'country':{}, 'phone':{}, 'email':{'required':1}} # the default value is {'required':0, 'type':'string', 'to_encrypt':'', 'to_upper':0}
data_to_be_save = {'user_id':'user_name', 'password':'user_passwd', 'first_name':'first_name', 'last_name':'last_name', 'company':'company', 'street':'street', 'city':'city', 'state':'state', 'zip':'zip', 'country':'country', 'phone':'phone', 'email':'email'}

def produceStr(v, sep='"'):
	if type(v) is types.StringType: return sep + v + sep
	return repr(v)

my_vars = {'ui_logon':script_path_url+'/ui'}


# read data from cgi form.
form_data = {}
form = cgi.FieldStorage()
for k,v in data_set.items():
	if form.has_key(k):
		fv = form.getvalue(k).strip()
		if not fv:
			if v.get('required', 0): error_info.append("Error: required items (%s) didn't supplied!" % k)
			continue
		if v.get('type', 'string') != 'string': pass # need to some transformation here if there is any data other than string to be used.
		if v.get('to_upper',0): fv = fv.upper()
		if v.get('to_encrypt', '') == 'md5': fv = myMD5(fv)
		form_data[k] = fv
	elif v.get('required', 0):
		error_info.append("Error: required items (%s) didn't supplied!" % k)
		#break

# check user_id
if not re.match(r'^[a-zA-Z0-9_]+$', form_data.get('user_id', 'a')): error_info.append('Error: Invalid characters in the user ID!') 

# check password
if form_data.has_key('password') and form_data.has_key('password_confirm') and form_data['password'] != form_data['password_confirm']:
	error_info.appdne("Error: passwords doesn't match!")

#check email
if not re.match(r'^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+', form_data.get('email', 'a@a.a')): error_info.append('Error: Invalid email address!')

# check user_name in db

connection, cursor = getConnectionCursor()
 
cursor.execute('LOCK TABLES users WRITE')
if form_data.get('user_id', ''):
	sql_statement = 'SELECT user_name FROM users WHERE user_name="%s"' % form_data['user_id'] 
	n = cursor.execute(sql_statement)
	if n: error_info.append("Error: user Id (%s) is already in use!" % form_data['user_id'])
	#result_set = cursor.fetchall()

if error_info: # exit
	cursor.execute('UNLOCK TABLES')
	connection.close()
	exitWithInfo()
else:	#update db
	vars_available = filter(data_to_be_save.has_key, form_data.keys())
	values_available = map(form_data.get, vars_available)
	fields_related = map(data_to_be_save.get, vars_available)
	fields_related.append('register_time')
	fields_str = ', '.join(fields_related)
	#values_str = repr(tuple(values_available))[1:-1]
	values_str = ", ".join(map(produceStr, values_available))
	date_time = time.strftime(', "%Y-%m-%d %H:%M:%S"', time.gmtime())
	sql_statement = ("INSERT INTO users (%s) VALUES (" % fields_str) + values_str + date_time + ')'
	
	#exitWithInfo(values_str+'<p>'+sql_statement)

	#lg = open('logs.txt', 'wt')
	#lg.write(sql_statement)
	#lg.close()

	n = cursor.execute(sql_statement) 
	if not n:# check if it is successful or not
		error_info.append('Error: failed to update databases. The server faces problem at this moment. Please try later.')

cursor.execute('UNLOCK TABLES')
connection.close()

if error_info: exitWithInfo()

# send confirm email:
msg = '''To: %s
From: xxia@skcc.org
Bcc: xxia@skcc.org
Subject: Confirm registration on WebArray

Dear %s:

Please confirm your registration - click the following URL or copy it to a browser's address bar.

%s

Thanks for your interest in WebArray.

- WebArray
'''
#msg = "To: %s\nFrom: WebArray at SKCC\nSubject: Confirm registration\n\nDear %s:\n\nPlease confirm your registration - by click the following URL or copy it to a browse's address bar.\n\n%s\n\nThanks for you interest in our analysis system.\n\n- webarray\n"

from tools import encodeStr
thd = 'http://%s%s/confirm/%s' % (http_host, script_path_url, encodeStr(form_data['user_id']))
#thd = 'http://'+http_host+'/'+script_path_url+'/confirm/'+encodeStr(form_data['user_id'])
msg = msg % (form_data['email'], form_data['first_name'], thd)
MAIL = '/usr/sbin/sendmail'
p = os.popen('%s -t' % MAIL, 'w')
p.write(msg)
exitcode = p.close()

print cgi_token

if exitcode != 0:
	print "An email was sent to %s. Please check it to confirm your registration as %s, " % (form_data['email'], form_data['user_id'])
	print "<p>click <a href='%s'>Here</A> TO Logon." % my_vars['ui_logon']
else:
	print '<p> Exit code ', exitcode, '<br>'

#print "click <a href='ui/logon'>Here</a> to logon."
#from

#print cgi.print_environ() 

