#!/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 = {'ui_upload':script_path_url+'/ui/upload', 'page_intro':script_path_url+'/ui/intro'}

#base_upload_dir = 'data'
#data_subdirs = {'intensity':['intensity', 'intensity_file'], 'gal':['gal', 'gal_file'], 'spot':['spot','spot_file']} # the key, is items to be dealt with, the value is [dir_name, name_from_cgi]

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

#home_dir = base_dir # /var/www, or '/home/xxia/public_html' # user data will based on this dir
#users_relative_dir = "users"
#user_parent_dir = os.path.join(home_dir, users_relative_dir) # /var/www/users, or /home/xxx/public_html/users
#user_id = username.lower() 
#user_dir = os.path.abspath(os.path.join(user_parent_dir, user_id))
#upload_dir = os.path.join(user_dir, base_upload_dir)
#if not os.path.exists(upload_dir): os.makedirs(upload_dir)
#for k, v in data_subdirs.items():
#	v[0] = os.path.join(upload_dir, v[0])
#	if not os.path.exists(v[0]): os.mkdir(v[0])

if username == 'demo' and freeze_demo:
	print cgi_token
	#print '<META HTTP-EQUIV="refresh" CONTENT="5;URL=%s">' % my_vars['ui_upload']
	print "<title>Results of analysis</title>"
	print "<body bgcolor='white'>\n"
	print "The demo user has no privilege to upload files!" % n
	#print "<p>Wait 5 seconds to <a href=%s>upload more files</a>, or <a href=%s>return to homepage</a>" % (my_vars['ui_upload'], my_vars['page_intro'])
	print "</body>"
	sys.exit(0)

path_info = os.getenv('PATH_INFO')
if path_info: path_info = unescape(path_info)
if path_info: path_info = path_info[1:] # remove the leading '/'
else: sys.exit(0)

#open('/home/xxia/temp/path_info.txt', 'w').write(username + ' : ' + path_info + '\n')

os.umask(002)
prepareUploadDirs()

user_agent = os.getenv('HTTP_USER_AGENT')
if 'Windows' in user_agent: user_system = 'Win'
elif 'Mac' in user_agent: user_system = 'Mac'
else: user_system = 'other'

import codecs
def recodeWithUTF8(s):
	if s.startswith(codecs.BOM_UTF32_BE): return s[4:].decode('utf-32-be').encode('utf-8')
	elif s.startswith(codecs.BOM_UTF32_LE): return s[4:].decode('utf-32-le').encode('utf-8')
	elif s.startswith(codecs.BOM_UTF16_BE): return s[2:].decode('utf-16-be').encode('utf-8')
	elif s.startswith(codecs.BOM_UTF16_LE): return s[2:].decode('utf-16-le').encode('utf-8')
	elif s.startswith(codecs.BOM_UTF8): return s[3:]
	else: return s

# Retrieve data from user
form = cgi.FieldStorage()
n = 0
if not (freeze_demo and username=='demo'):
	v = data_subdirs.get(path_info, None)
	#for v in data_subdirs.values():
	if v:
		sub_dir, name_html = v['name_full'], 'file' #v['name_cgi']
		#open('/home/xxia/temp/path_info.txt', 'a').write(sub_dir + '\n')
		bin_type, bin_ext = v.get('binary_file', False), v.get('binary_ext', [])
		if form.has_key(name_html):
			#files = form.getlist(name) # raw_data_files should have several files
			files = form[name_html]
			if type(files) != type([]): files = [files]
			for afile in files:
				if not afile.file or not afile.value: continue
				filename = afile.filename
				if user_system == 'Win': st = filename.rfind('\\')
				elif user_system == 'Mac': st = filename.rfind(':')
				else: st = filename.rfind('/')
				filename = filename[st+1:]
				filename = os.path.join(sub_dir, filename)
				fp = open(filename, "wb")
				# check if need to decode/encode to UTF-8
				ext = os.path.splitext(filename)[1][1:].upper()
				if bin_type or ext in bin_ext: # is a binary file
					fp.write(afile.value)
				else: # is a text file
					fp.write(recodeWithUTF8(afile.value))
				fp.close()
				n += 1

query_str = os.getenv('QUERY_STRING')
if query_str and query_str=='db': my_vars['ui_upload'] = script_path_url+'/ui/dbs_upload.pih'

print cgi_token
#print '<META HTTP-EQUIV="refresh" CONTENT="5;URL=%s">' % my_vars['ui_upload']
print "<title>Results of analysis</title>"
print "<body bgcolor='white'>\n"
print "%d files were uploaded successfully!" % n
#print "<p>Wait 5 seconds to <a href=%s>upload more files</a>, or <a href=%s>return to homepage</a>" % (my_vars['ui_upload'], my_vars['page_intro'])


#import cgi
#print cgi.print_environ()
#print '\n\n'
#print cgi.print_environ_usage()

#print '<p>',form

print "</body>"


