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

"""Main Controller"""

from tg import expose, flash, require, url, request, redirect, validate, tmpl_context
from pylons.i18n import ugettext as _, lazy_ugettext as l_
from catwalk.tg2 import Catwalk
from repoze.what import predicates

from quizz.lib.base import BaseController
from quizz.model import DBSession, metadata
from quizz.controllers.error import ErrorController
from quizz import model
from quizz.controllers.secure import SecureController

from quizz.model import Quizz, Question, Proposition, Test, Reponse, User, Group
from quizz.widgets.reponse_form import create_reponse_form

from datetime import datetime

__all__ = ['RootController']


class RootController(BaseController):
    """
    The root controller for the Quizz application.
    
    All the other controllers and WSGI applications should be mounted on this
    controller. For example::
    
        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()
    
    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.
    
    """
    secc = SecureController()
    
    admin = Catwalk(model, DBSession)
    
    error = ErrorController()

    @expose('quizz.templates.index')
    def index(self):
        """Handle the front-page."""
	quizzs = DBSession.query(Quizz).all()
        user = DBSession.query(User).filter_by(
            user_id=request.identity['user'].user_id).one()
	tests = DBSession.query(Test).filter_by(
            id_utilisateur = user.user_id).all()
        tests = dict([(t.id_quizz, t) for t in tests])
        return dict(quizzs=quizzs, tests=tests)

    @expose('quizz.templates.quizz')
    def quizz(self, id):
        quizz = DBSession.query(Quizz).filter_by(id=id).one()
	test = DBSession.query(Test).filter_by(id_quizz=id).all()
        if len(test) == 0:
            test = Test()
            test.date = datetime.now()
            test.id_utilisateur = request.identity['user'].user_id
            test.id_quizz = quizz.id
            DBSession.add(test)
            DBSession.flush()
        else:
            test = test[0]
        tmpl_context.form = create_reponse_form
        propositions = dict([(q.id, [(p.id, p.name) for p in q.propositions]) for q in quizz.questions])
        reponses = [r.id_proposition for r in test.reponses]
        repondues = [r.id_question for r in test.reponses]
        termine = len(repondues) == len(quizz.questions)
        return dict(reponses=reponses,
		repondues=repondues,
		propositions=propositions,
		quizz=quizz, test=test, termine=termine)

    @validate(create_reponse_form, error_handler=quizz)
    @expose()
    def repondre(self, **kw):
        reponse = Reponse()
        reponse.id_test = kw['test']
        reponse.id_question = kw['question']
        reponse.id_proposition = kw['choix']
        reponse.weight = kw['poids']
        DBSession.add(reponse)
        DBSession.flush()
	flash(u"La réponse a bien été enregistrée")
        redirect('/quizz/%s' % reponse.question.id_quizz)



    @expose('quizz.templates.index')
    def scores(self):
        """Handle the front-page."""
	quizzs = DBSession.query(Quizz).all()
        users = DBSession.query(User).all()
        scores = dict()
        for quizz in quizzs:
            scores[quizz.id] = dict([(t.utilisateur.user_id, t.note_standard) for t in DBSession.query(Test).filter_by(id_quizz=quizz.id).all()])
        return dict(page='index', quizzs=quizzs, users=users, scores=scores)






    @expose('quizz.templates.about')
    def about(self):
        """Handle the 'about' page."""
        return dict(page='about')

    @expose('quizz.templates.authentication')
    def auth(self):
        """Display some information about auth* on this application."""
        return dict(page='auth')

    @expose('quizz.templates.index')
    @require(predicates.has_permission('manage', msg=l_('Only for managers')))
    def manage_permission_only(self, **kw):
        """Illustrate how a page for managers only works."""
        return dict(page='managers stuff')

    @expose('quizz.templates.index')
    @require(predicates.is_user('editor', msg=l_('Only for the editor')))
    def editor_user_only(self, **kw):
        """Illustrate how a page exclusive for the editor works."""
        return dict(page='editor stuff')

    @expose('quizz.templates.login')
    def login(self, came_from=url('/')):
        """Start the user login."""
        login_counter = request.environ['repoze.who.logins']
        if login_counter > 0:
            flash(_('Wrong credentials'), 'warning')
        return dict(page='login', login_counter=str(login_counter),
                    came_from=came_from)
    
    @expose()
    def post_login(self, came_from=url('/')):
        """
        Redirect the user to the initially requested page on successful
        authentication or redirect her back to the login page if login failed.
        
        """
        if not request.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect(url('/login', came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=url('/')):
        """
        Redirect the user to the initially requested page on logout and say
        goodbye as well.
        
        """
        flash(_('We hope to see you soon!'))
        redirect(came_from)

