#!/usr/bin/python
# -*- coding: iso-8859-1 -*-

####
# Copyright (C) 2006, 2007 Kim Gerdes
# kim AT gerdes.fr
#
# This program is free software; you can redistribute it and/or
 # modify it under the terms of the GNU General Public License
 # as published by the Free Software Foundation; either version 2
 # of the License, or (at your option) any later version.
#
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
# See the GNU General Public License (www.gnu.org) for more details.
#
# You can retrieve a copy of the GNU General Public License
# from http://www.gnu.org/.  For a copy via US Mail, write to the
#     Free Software Foundation, Inc.
#     59 Temple Place - Suite 330,
#     Boston, MA  02111-1307
#     USA
####


import time, re, cgitb, cgi,sha, Cookie, os,sys,shelve
cgitb.enable()
import session

machine = "elizia.net"
cefichier = "histoire.cgi"
stylesheet = "/eliziastyle.css" # avec chemin depuis machine




def Walk( root, recurse=0, pattern='*', return_folders=0 ):
	import fnmatch, os, string
	
	# initialize
	result = []

	# must have at least root folder
	try:
		names = os.listdir(root)
	except os.error:
		return result

	# expand pattern
	pattern = pattern or '*'
	pat_list = string.splitfields( pattern , ';' )
	
	# check each file
	for name in names:
		fullname = os.path.normpath(os.path.join(root, name))

		# grab if it matches our pattern and entry type
		for pat in pat_list:
			if fnmatch.fnmatch(name, pat):
				if os.path.isfile(fullname) or (return_folders and os.path.isdir(fullname)):
					result.append(fullname)
				continue
				
		# recursively scan other folders, appending results
		if recurse:
			if os.path.isdir(fullname) and not os.path.islink(fullname):
				result = result + Walk( fullname, recurse, pattern, return_folders )
			
	return result
			
			
def outputForRogers(cas,keywords,answers):
	res = "keywords['"+cas+"'] = ["
	for key in keywords:
		res += '"' +key+ '", '
	res = res[:-1]+"]<br>"
	res += "answers['"+cas+"'] = ["
	for ans in answers:
		res += '"' +ans+ '", '
	res = res[:-2]+"]"
	return res





print "Content-Type: text/html\n" # blank line : end of headers

print """<html>
	<head><title> Histoire d'elizia </title><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
	"""
print	'<link href="http://' + machine + stylesheet+'" rel="stylesheet" type="text/css"></head>'


print "<body > <h1> L'histoire d'elizia </h1>"



files = Walk(os.environ['DOCUMENT_ROOT'] + '/session', 0, 'sess*', 1)
print '<h3>Nous avons %s sessions de thérapie enregistrées:</h3>' % len(files)


for file in files:
	print "<hr><br>"
	
	sid = file[-40:]
	data = shelve.open(os.environ['DOCUMENT_ROOT'] + '/session'+'/sess_' + sid, writeback=False)
	specialAnswers = data.get('specialAnswers')
	#if not specialKeys :continue	
	if data.get('firstvisit') :
		print "<h4>Session commencée le "+time.asctime(time.localtime(float(data["firstvisit"])))+"</h4>"
	if "ipnum" in data.keys() :
		print "<h4>"+data["ipnum"]+"</h4>"
	print " --- " +sid + "<br>"	

	
	specialKeys = data.get('specialKeys')
	if specialAnswers :
		
		for c in specialAnswers.keys():
			print  "<tr><table style='border:thin solid red; border-spacing:5px ;font-size: small; empty-cells:show; width:100%'>"
			print "<tr>: : : "+c+"</tr>"
	
			print '<tr><td>'
			if c in specialKeys.keys():
				print '<textarea name="keys" cols="30" rows="8" style=" font-size: x-small; height:100%; width:100%;">'
				for key in specialKeys[c]:
					print key
				print '</textarea>'
			else : print "cléfs spéciales"
			print "</td><td class='elizia'>"
			print '<textarea name="answers" cols="80" rows="8" >'
			for rep in specialAnswers[c]:
				print rep
			print '</textarea></td></tr>'
			print '<tr><td colspan="2" >'
			if c in specialKeys.keys():
				print "<p style='font-size: xx-small; color:grey;'>"+outputForRogers(c,specialKeys[c],specialAnswers[c])+"</p>"
			print '</td></tr>'
			
			print '</table></tr>'
			
	
	
	print  "<table style='border:thin solid red; border-spacing:10px ; empty-cells:show; width:100%'>"
	
	
	if "memoireReponses" in data.keys():
		for i in range(len(data["memoireReponses"])):
			print "<tr ><td class='tech' style='width:115px'>"+time.asctime(time.localtime(float(data["memoireTemps"][i]))),
			print " : </td><td><span class='vous' >"+data["memoireinputsPatient"][i]+"</span> </td><td> <span class='elizia'>",
			print data["memoireReponses"][i],
			print "<td class='tech' style='width:77px'>"+data["memoireCas"][i]+"</td></tr>"


	print "</table>"
print "<br><br><br><P> </p>"
print '<div class="tech">'
print "<p><b><u>trucs techniques :</u></b></p>"






print "<p><b>Referer:</b>", os.environ.get("HTTP_REFERER", "<not present>")
print "<p><b>User Agent:</b>", os.environ.get("HTTP_USER_AGENT", "<unknown>")
ipnum = os.environ.get("REMOTE_ADDR", "<not present>")
print "<p><b>IP:</b>", ipnum
print '</div>'
print "</body></html>"