from mod_python import apache
from mod_python import util
from mod_python import Cookie
import os
import sys
import re
import uris as uri
import time
tab = "\t\t\t\t"
sys.path.append('/afs/csl.tjhsst.edu/users/jsherwoo/web-docs/inc/')
cookies = None
requestObj = None
flags = None
#my packages
import elements as e
import sql
import USER as user
def parsequery(querystring):
	r = {}
	for pairing in querystring.split('&'):
		if pairing == '':pass
		if '=' in pairing:
			r.setdefault(*pairing.split('='))
		else:
			r[pairing] = True
	return r

def load(module, loadUser = True):
	global cookies, requestObj, flags
	module.e = e
	module.sql = sql
	module.Cookie = Cookie
	module.cookies = cookies
	module.requestObj = requestObj
	module.flags = flags
	if loadUser:
		module.user = user
	module.load = load

def handler(req):
	global tab, cookies, requestObj, flags
	requestObj = req
	cookies = Cookie.get_cookies(req)
	scheme, hostinfo, username, password, hostname, port, path, query, fragment = req.parsed_uri
	template, args = uri.det(query.split('|')[0])
	flags = parsequery(query.split('|')[1])
	e.flags = flags
	e.formdata = util.FieldStorage(req)
	view = __import__(template,[],[],[template.split('.')[-1]])
	view.wrap = lambda **x:x
	load(user, False)
	load(view)
	user.init(req)
	data = view.render(*args)
	attributes = data.keys()
	if 'plainrender' in attributes:
		if 'content-type' not in attributes:
			data['content-type'] = 'text/html'
		req.content_type = data['content-type']
		req.write(str(data['html']))
		return apache.OK
	if 'error' in attributes:
		if data['error'] == 404:
			data['title'] = 'File Not Found'
			data['html'] = '<p>The page you requested could not be located.  If you were directed to this page from an internal link, please contact an administrator.</p>\n'
			if 'debug' in flags:data['html'] += '<p>%s</p>'%template
		if data['error'] == 401:
			data['title'] = 'Login Required'
			data['html'] = '<p>You must be logged in to view this page.</p>\n'
		attributes = data.keys()
	if 'html' not in attributes: data['html'] = '<p>Empty Response</p>'
	if 'title' not in attributes: data['title'] = 'Page'
	if 'template' not in attributes: data['template'] = 'default'
	if 'content-type' not in attributes: data['content-type'] = 'text/html'
	if 'options' not in attributes: data['options'] = []
	req.content_type = data['content-type']
	if data['template'] is not None:
		header = __import__('template.%s_header'%data['template'],[],[],['%s_header'%data['template']])
		req.write(header.render(title = data['title'], options = data['options']))
	if data['content-type'] == 'text/html':
		for line in data['html'].split("\n"):
			req.write(tab+line+"\n")
	else:
		req.write(data['html'])
	if data['template'] is not None:
		footer = __import__('template.%s_footer'%data['template'],[],[],['%s_footer'%data['template']])
		req.write(footer.render())
	return apache.OK
