#!/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, cgitb, cgi, Cookie, os
import session
from analyste import Elizia

# web debug output:
cgitb.enable()

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

def connaissance(total_seconds):
	""" 	traduit un nombre de secondes
		en phrase de durée
	"""
	if total_seconds <1 :
		return "On est en train de faire connaissance"
	else :
		seconds = total_seconds % 60
		total_minutes = total_seconds / 60
		minutes = total_minutes % 60
		total_hours = total_minutes / 60
		hours = total_hours % 24
		total_days = total_hours / 24
		days = total_days % 365
		years = total_days / 365
		text = "On se connait depuis plus de "
		per = [years, days, hours, minutes, seconds]
		pernom = ['année', 'mois', 'heure', 'minute', 'seconde']
		for i in range(len(per)):
			if per[i] :  
				text+= str(per[i]) + " "+pernom[i]
				if per[i]>1 : text+= "s"
				break
		return text+". Ça va déjà mieux ?"
	


sess = session.Session(expires=365*24*60*60, cookie_path='/')
# expires can be reset at any moment: sess.set_expires('') 
# or changed: sess.set_expires(30*24*60*60) Session data is a dictionary like object

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

print """<html>
	<head><title> 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 OnLoad='document.entree.probleme.focus();'> "

print """<div id="analyzebox">"""

#print """</div>"""	
	
print "<h2> Relaxez-vous - vous êtes chez Elizia </h2>"

e = Elizia()

DBmessage = e.linguist.dataBaseStatus

form = cgi.FieldStorage()
probleme = ""
if form.has_key("probleme") :
	probleme = form["probleme"].value
	print "<p class = 'vous'>Vous :",probleme,"</p>"
	print "<p class = 'elizia'>Elizia :",e.analyse(probleme,sess),"</p>"
else  :
	if os.environ.get("HTTP_REFERER", "<not present>").endswith("elizia.cgi") :
		print "<p class = 'vous'>Vous :",probleme,"</p>"
		print "<p class = 'elizia'>Elizia :",e.analyse(probleme,sess),"</p>"
	else : 
		print "<p class = 'elizia'>Elizia : Mettez-vous à l'aise et parlez-moi ouvertement de vos problèmes !</p>"
	
# mettre le champ d'entrée
if not e.fini: print '<form method="post" action="'+cefichier+'" name="entree"><input name="probleme" class="probleme" ></form>'

print "</div><br>"
print '<div id="tetebox"></div>'

# history
print '<div class="history">'


if "memoireReponses" in sess.data.keys():
	print "<p><b><u>Historique de votre thérapie :</u></b></p>"
	for i in range(len(sess.data["memoireReponses"])):
		print  "<p><span class = 'temps'>"+time.asctime(time.localtime(float(sess.data["memoireTemps"][i]))),
		print " : &nbsp;&nbsp;&nbsp;&nbsp;</span><span class = 'vous'>"+sess.data["memoireinputsPatient"][i]+" </span>-<span class = 'elizia'> ",
		print sess.data["memoireReponses"][i],
		print "</span></p>"
		
	

firstvisit = sess.data.get('firstvisit')
lastvisit = sess.data.get('lastvisit')
if firstvisit and lastvisit : 
	therapyduration = float(lastvisit)-float(firstvisit)
	print "<p>", connaissance(int(therapyduration)),"</p>"
else : 
	therapyduration = float(0)
	message = '<p>New session</p>'
	sess.data['firstvisit'] = repr(time.time())
	firstvisit = repr(time.time())
	lastvisit = repr(time.time())

# Save lastvisit in the session
sess.data['lastvisit'] = repr(time.time())
ipnum = os.environ.get("REMOTE_ADDR", "<not present>")
sess.data['ipnum'] = ipnum

print '</div>'

print """<div id="bottombox"><a  href="http://"""+machine+"""/cerveau">Le cerveau d'Elizia</a>
	&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;<a href="supervision.cgi">La supervision</a> 
	&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;<a href="regex">Un exercice sur les expressions régulières</a> 		
	</div>
	"""
	
print '<div id="cervobox"></div>'

print "</body></html>"
sess.close()