# -*- coding: utf-8 -*-


__author__ = "Sébastien CHAZALLET"
__copyright__ = "Copyright 2012"
__credits__ = ["Sébastien CHAZALLET", "InsPyration.org", "Éditions ENI"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Sébastien CHAZALLET"
__email__ = "sebastien.chazallet@laposte.net"
__status__ = "Production"


from Tkinter import *
import tkSimpleDialog

from datetime import datetime

from paste.deploy import appconfig
from pylons import config
from quizz.config.environment import load_environment
conf = appconfig('config:development.ini', relative_to='.')
load_environment(conf.global_conf, conf.local_conf)
import transaction
import atexit

from quizz.model import *

class Manager:

	@staticmethod
	def certitudes():
		return ((1, "Je répond par défaut"),
			(2, "Je pense que c'est çà"),
			(3, "Je suis sur de moi"))

	@classmethod
	def register_user(cls, username, password):
		users = DBSession.query(User).filter_by(user_name=username).all()
		if len(users) == 1:
			u = users[0]
			if u.validate_password(password):
				cls.user = u
				tests = DBSession.query(Test).filter_by(
					id_utilisateur = u.user_id).all()
				cls.tests = dict([(t.id_quizz, t) for t in tests])
				return True
		return False

	@classmethod
	def is_user_registered(cls):
		return hasattr(cls, 'user')

	@staticmethod
	def getQuizzs():
		return DBSession.query(Quizz).all()

	@staticmethod
	def getQuizzTitles():
		result = []
		for q in DBSession.query(Quizz).all():
			test = Manager.tests.get(q.id)
			if test is None:
				nb_reponses = 0
			else:
				nb_reponses = len(test.reponses)
			text = '%s (%s/%s)' % (q.name, nb_reponses, len(q.questions))
			result.append((q, text))
		return result

	@classmethod
	def show_quizz(cls, quizz):
		print('Quizz choisi %s' % quizz.id)
		if quizz.id not in cls.tests.keys():
			print('Création d\'un nouveau test')
			test = Test()
			test.date = datetime.now()
			test.id_utilisateur = cls.user.user_id
			test.id_quizz = quizz.id
			DBSession.add(test)
			DBSession.flush()
			cls.test = test
		else:
			cls.test = cls.tests[quizz.id]
			print('Réponses/Questions: %s/%s' % (len(cls.test.reponses), len(quizz.questions)))
			print quizz.questions
			print cls.test.reponses
		repondues = [r.id_question for r in cls.test.reponses]
		cls.questions = [qt for qt in quizz.questions if qt.id not in repondues]
		if len(cls.questions) == 0:
			cls.question = None
		else:
			cls.question = cls.questions.pop(0)
		f = FormFrame()
		f.build(quizz)

	@classmethod
	def propositions(cls):
		return [(p.id, p.name) for p in cls.question.propositions]

	@classmethod
	def next(cls):
		cls.questions.append(cls.question)
		cls.question = cls.questions.pop(0)

	@classmethod
	def validate(cls, proposition, certitude):
		print("Enregistrement de la proposition de réponse %s pour la question %s avec la certitude %s" % (proposition, cls.question.id, certitude))
		reponse = Reponse()
		reponse.id_test = cls.test.id
		reponse.id_question = cls.question.id
		reponse.id_proposition = proposition
		reponse.weight = certitude
		DBSession.add(reponse)
		DBSession.flush()
		if len(cls.questions) == 0:
			cls.question = None
		else:
			cls.question = cls.questions.pop(0)

class Command:
	def __init__(self, callback, **kw):
		self.callback = callback
		self.kw = kw
	def __call__(self):
		self.callback(**self.kw)

white_style = {
	'bg': "white",
	'activebackground': "white",
	'highlightbackground': "white",
}

pink_style = {
	'bg': "pink",
	'activebackground': "red",
}

blue_style = {
	'bg': "light blue",
	'activebackground': "cyan2",
}

alt_style = {
	'bg': "white",
	'activebackground': "light blue",
	'highlightbackground': "ivory1",
}

class FormFrame(Frame):
	def __init__(self):
		self.root = Tk()
		self.root.geometry("800x600")
		self.root.title("Répondre à un quizz")
		Frame.__init__(self, self.root, width=800, height=600, bg="white")
		self.certitude = IntVar(master=self.root, value=2)
		self.proposition = IntVar(master=self.root)

	def build(self, quizz):
		self.paned = PanedWindow(self.root, orient=VERTICAL)
		self.topcontent = LabelFrame(self.paned, text="Actions", bg="white")
		Button(self.topcontent, text="Quitter", command=self.root.destroy, **pink_style).pack(side=LEFT)
		self.contextuals = []
		w = Button(self.topcontent, text="Sauter au Suivant", command=self.next, **pink_style)
		w.pack(side=LEFT)
		self.contextuals.append(w)
		w = Button(self.topcontent, text="Valider la réponse", command=self.validate, **blue_style)
		w.pack(side=LEFT)
		self.contextuals.append(w)
		self.paned.add(self.topcontent)
		self.maincontent = LabelFrame(self.paned, text=quizz.name, bg="white")
		for v, t in Manager.certitudes():
			w = Radiobutton(self.maincontent, text=t, variable=self.certitude, value=v, **white_style)
			w.pack(anchor=W)
			self.contextuals.append(w)
		Label(self.maincontent, text="", bg="white").pack(anchor=W)
		if Manager.question is None:
			self.question = Label(self.maincontent, text="Quizz terminé", bg="white")
		else:
			self.question = Label(self.maincontent, text="Question: %s" % Manager.question.name, bg="white")
		self.question.pack(anchor=W)
		w = Label(self.maincontent, text="Propositions: ", bg="white")
		w.pack(anchor=W)
		self.contextuals.append(w)
		if Manager.question is not None:
			self.build_proposition()
		else:
			self.affiche_resultat()
		self.paned.add(self.maincontent)
		self.paned.pack(expand="yes",fill="both")
	def build_proposition(self):
		self.widgets_variables = []
		for v, t in Manager.propositions():
			w = Radiobutton(self.maincontent, text=t, variable=self.proposition, value=v, **white_style)
			w.pack(anchor=W)
			self.widgets_variables.append(w)
	def next(self):
		Manager.next()
		self.change_question()
	def validate(self):
		if self.proposition.get() == 0:
			return
		Manager.validate(self.proposition.get(), self.certitude.get())
		self.change_question()
	def change_question(self):
		for w in self.widgets_variables:
			w.destroy()
		if Manager.question is None:
			self.question.configure(text="Quizz terminé")
			self.affiche_resultat()
		else:
			self.question.configure(text="Question: %s" % Manager.question.name)
			self.build_proposition()
	def affiche_resultat(self):
		Label(self.maincontent, text="", bg="white").pack(anchor=W)
		Label(self.maincontent, text="Résultat: ", bg="white").pack(anchor=W)
		Label(self.maincontent, text="Note standard: %s" % Manager.test.note_standard, bg="white").pack(anchor=W)
		text = "Note Pondérée: %s (%s - %s)" % (Manager.test.note_ponderee, Manager.test.note_ponderee_positive, Manager.test.note_ponderee_negative)
		Label(self.maincontent, text=text, bg="white").pack(anchor=W)
		for w in self.contextuals:
			w.destroy()

class App(Frame):
	def __init__(self):
		self.root = Tk()
		self.root.title("Application Quizz")
		Frame.__init__(self, self.root, bg="white")
		self.button_quit = Button(self, text="Veuillez saisir vos identifiants", **pink_style)
		self.button_quit.pack(side=TOP)
		self.pack()
	def build(self):
		self.button_quit.configure(text="Quitter", command=self.quit)
		self.maincontent = LabelFrame(self, text="Liste des quizz", bg="white")
		self.maincontent.pack(fill="both", expand="yes")
		for q, text in Manager.getQuizzTitles():
			Button(self.maincontent, text=text, command=Command(Manager.show_quizz, quizz=q), **alt_style).pack(side=TOP, fill=X)
		self.mainloop()





class AuthDialog(tkSimpleDialog.Dialog):
	def body(self, root):
		Label(root, text="Login:").grid(row=0)
		Label(root, text="Mot de passe:").grid(row=1)
		self.e1 = Entry(root)
		self.e2 = Entry(root, show='*')
		self.e1.grid(row=0, column=1)
		self.e2.grid(row=1, column=1)
		return self.e1
	def apply(self):
		Manager.register_user(unicode(self.e1.get()), unicode(self.e2.get()))

if __name__ == "__main__":
	app = App()
	d = AuthDialog(app.master)
	if Manager.is_user_registered():
		atexit.register(transaction.commit)
		app.build()






#		Label(self, text='Réponse 1',width=15).pack(side=LEFT)
#		Button(self, text="Par défaut", command=self.quit).pack(side=LEFT)
#		Button(self, text="Par déduction", command=self.quit).pack(side=RIGHT)
#		Button(self, text="Certitude", command=self.quit).pack(side=RIGHT)

