#!/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
import session
from random import choice
from frenchLinguist import FrenchLinguist
from rogers import Rogers
from analyste import Elizia

cgitb.enable()

# Some hosts will need to have document_root appended
# to sys.path to be able to find user modules
#sys.path.append(os.environ['DOCUMENT_ROOT'])

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


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


def connaissance(total_seconds):

	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
	





e = Elizia()

DBmessage = e.linguist.dataBaseStatus

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


print """<html>
	<head><title>Supervision Elizia </title>
	<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">"""
print """<style type="text/css">
	td { border:thin solid #ddd; }
	</style>"""
print	'<link href="http://' + machine +stylesheet+ '" rel="stylesheet" type="text/css"></head>'
print "<body OnLoad='document.entree.probleme.focus();'> <h1> Supervision d'<a href='http://elizia.net'>Elizia</a></h1>"
print "<p>Ici, on peut changer les réponses d'<a href='http://elizia.net'>Elizia</a> :</p><p>Les déclencheurs des cas spéciaux sont codés en dur, donc non-modifiable ici. Le cas 'Reprise' remplace 'xxx' avec le nom d'un cas reconnu avant dans la conversation. Le nom d'une section est donc important. Les réponses sont choisies dans un ordre arbitraire, en essayant d'éviter des répétitions directe. Dans le cas 'Insulte', les réponses sont données dans l'ordre et <a href='http://elizia.net'>Elizia</a> prend congé quand elle n'a plus de réponse.</p>"
print "<p>Dans la section 'cas normaux' vous pouvez changer les mots clés déclencheurs ainsi que les réponses.</p><p></p>"
print "<p>Tout en bas, vous pouvez créer un nouveau cas avec des mots clés et des réponses de votre choix.</p>"
print "<p>N'oubliez pas de cliquer sur 'Mettre à jour' quand vous avez changé quelque chose.</p>"
print "<p>Dans le champ d'Eliza ci-dessous, vous pouvez tester si tout marche comme vous le souhaitez. Les changements ne s'appliquent que pour vous (vous avez un cookie grâce auquel <a href='http://elizia.net'>Elizia</a> vous reconnaît) mais ils sont enrégistrés et si vos idées sont bonnes, on s'en inspirera...	</p><br><br>"


# get already saved special cases
specialKeys = sess.data.get('specialKeys')
specialAnswers = sess.data.get('specialAnswers')

if specialKeys :
	for c in specialKeys.keys():
		e.rogers.keywords[c]= specialKeys[c]
else :  specialKeys={}

if specialAnswers : 
	for c in specialAnswers.keys():
		e.rogers.answers[c]= specialAnswers[c]
else :	specialAnswers={}


form = cgi.FieldStorage()
probleme = ""

if form.has_key("cas") :
	keys = None
	cas = form["cas"].value
	if form.has_key("probleme") : probleme = form["probleme"].value
	if form.has_key("keys") : keys = [k.strip() for k in form["keys"].value.split("\n") if k.strip()]
	answers = [a.strip() for a in form["answers"].value.split("\n") if a.strip()]
	
	if keys : e.rogers.keywords[cas]= keys
	e.rogers.answers[cas]=answers
	if keys :specialKeys[cas]= keys
	specialAnswers[cas]=answers
	if specialKeys : sess.data['specialKeys'] = specialKeys
	if specialAnswers : sess.data['specialAnswers'] = specialAnswers



if not form.has_key("probleme") :
	if os.environ.get("HTTP_REFERER", "<not present>").endswith(cefichier) :
		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>"
else  :
	probleme = form["probleme"].value
	print "<p class = 'vous'>Vous :",probleme,"</p>"
	print "<p class = 'elizia'>Elizia :",e.analyse(probleme,sess),"</p>"
	

if not e.fini: print '<form method="post" action="'+cefichier+'" name="entree"><input  name="probleme" class="probleme" ></form>'

print "<p><br><br>"

print "<br><br><h2><u>Cas spéciaux :</u></h2>"

for cas in e.rogers.answers.keys():
	if cas in e.rogers.keywords.keys():
		continue
	print '<form method="post" action="'+cefichier+'" name="entree">'
	print '<input type="hidden" name="cas" value="'+cas+'">'
	print '<input type="hidden" name="probleme" value="'+probleme+'">'
	print  "<table style='border:thin solid red; border-spacing:5px ;font-size: small; empty-cells:show; width:100%'>"
	print "<tr>: : : "+cas+"</tr>"
	
	print '<tr><td>'
	print "clés spéciaux"
	print "</td><td class='elizia'>"
	print '<textarea name="answers" cols="80" rows="8" >'
	for rep in e.rogers.answers[cas]:
		print rep
	print '</textarea></td>'
	print '</tr><tr><td></td><td>'
	print '<input type="submit" value=" Mettre à jour"; style="border:thin solid white; border-spacing:10px ;  width:100%">'
	print "</td></tr></table></form>"

print "<br><br><h2><u>Cas normaux :</u></h2>"

for cas in e.rogers.keywords.keys():
	print '<form method="post" action="'+cefichier+'" name="entree">'
	print '<input type="hidden" name="cas" value="'+cas+'">'
	print '<input type="hidden" name="probleme" value="'+probleme+'">'
	print  "<table style='border:thin solid red; border-spacing:5px ;font-size: small; empty-cells:show; width:100%'>"
	print "<tr>: : : "+cas+"</tr>"
	print '<tr><td style="width:30%;" >'
	print '<textarea name="keys" cols="30" rows="8" style=" font-size: x-small; height:100%; width:100%;">'
	for key in e.rogers.keywords[cas]:
		print key
	print '</textarea>'
	
	print "</td><td width='70%' style='width:70%;' class='elizia'>"
	print '<textarea name="answers" style="width:100%;"   rows="8" >'
	for rep in e.rogers.answers[cas]:
		print rep
	print '</textarea></td>'
	print '</tr><tr><td></td><td>'
	print '<input type="submit" value=" Mettre à jour"; style="border:thin solid white; border-spacing:10px ;  width:100%">'
	print "</td></tr></table>"
	#print "<p style='font-size: xx-small;'>"+outputForRogers(cas)+"</p>"
	print "</form>"


	
print "<br><br><h2><u>Nouveau cas :</u></h2>"


print '<form method="post" action="'+cefichier+'" name="entree">'
print 'Nom du nouveau cas :<input name="cas"  >'
print '<input type="hidden" name="probleme" value="'+probleme+'">'
print  "<table style='border:thin solid red; border-spacing:5px ;font-size: small; empty-cells:show; width:100%'>"


print '<tr><td width="30%"><textarea name="keys" cols="30" rows="8" style=" font-size: x-small; height:100%; width:100%;">'
print "les mots clés (effacer cette ligne)"
print '</textarea>'
print "</td><td width='70%' class='elizia'>"
print '<textarea name="answers" cols="90"   rows="8" >'
print "au moins deux réponses (effacer cette ligne)"
print '</textarea></td>'
print '</tr><tr><td></td><td>'
print '<input type="submit" value=" Mettre à jour"; style="border:thin solid white; border-spacing:10px ;  width:100%">'
print "</td></tr></table></form>"


print "<br><br>"
print '<div class="tech">'
print "<p><b><u>trucs techniques :</u></b></p>"
memoire = sess.data.get('memoireinputsPatient')

print "<p><b>Cas : </b>"+e.cas+"</p>"
print "<p><b>Conversation : </b></p>"	
if "memoireReponses" in sess.data.keys():
	for i in range(len(sess.data["memoireReponses"])):
		print  "<p>"+time.asctime(time.localtime(float(sess.data["memoireTemps"][i]))),
		print " : "+sess.data["memoireinputsPatient"][i]+" - ",
		print sess.data["memoireReponses"][i],
		print "("+sess.data["memoireCas"][i]+")</p>"
		

firstvisit = sess.data.get('firstvisit')
lastvisit = sess.data.get('lastvisit')
if firstvisit and lastvisit : 
	therapyduration = float(lastvisit)-float(firstvisit)
	message = '<p>Welcome back. Your last visit was on ' + 	time.asctime(time.localtime(float(lastvisit))) +"</p>"
	print "<p>Your first visit was on " + time.asctime(time.localtime(float(firstvisit))) +"</p>"
	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 the current time in the session
sess.data['lastvisit'] = repr(time.time())
print message
print DBmessage+"<br>"
print "<p>sess.cookie : "+str(sess.cookie)+"</p>"
for i in sess.data.keys():
	if i=="memoireReponses" or i=="memoireinputsPatient" or i=="memoireTemps" or i=="memoireCas":
		pass
	else : print  "<p><b>"+i+": </b>"+str(sess.data[i])+"</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>")
sess.data['ipnum'] = ipnum
print "<p><b>IP:</b>", ipnum
print '</div>'
sess.close()
print "</body></html>"