# -*- coding: utf-8 -*-
"""Main Controller"""

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

import bazki

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

__all__ = ['RootController']


class RootController(BaseController):
    """
    The root controller for the Monkey 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()
    
    edit = bazki.Edit()
    edit.allow_only = predicates.in_any_group(u'Admin',
                                   msg=l_('Only Admins can edit this website!'))
    _default = bazki.Getter()
    bazki = bazki.Static()

    # These shouldn't be necessary, but TG2 doesn't document how
    # "default" is supposed to work, and this makes it DWIW
    @expose()
    def _lookup(self, *remainder):
        return self._default, remainder
    @expose()
    def index(self):
        return self._default._default()
    
    error = ErrorController()

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

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

    @expose('monkey.templates.login')
    def login(self, came_from='/'):
        """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='/'):
        """
        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('/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='/'):
        """
        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)
