"""The base Controller API

Provides the BaseController class for subclassing.
"""
import logging

from pylons.controllers import WSGIController
from pylons.templating import render_mako as render

from paste.deploy.converters import aslist

from ppdi.model.meta import Session
from ppdi.model import ModeratorPin

from pylons import session, url, config
from pylons.controllers.util import redirect, abort

log = logging.getLogger(__name__)

class BaseController(WSGIController):
    
    requires_auth = False
    
    def __before__(self):
        if self.requires_auth and not session.get('logged_in'):
            if session.get('after_login') is None:
                session.clear()
                if url.current() != url(controller='auth/login', action='index'):
                    session['after_login'] = url.current()
                else:
                    session['after_login'] = url('/')
                session.save()
                
            redirect(url(controller='auth/login', action='index'))

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()
            
    def is_my_pin(self, pin):
        """Checks if this is my pin, if not, raise a 403"""
        if self.checkAdmin(asbool=True):
            return
            
        obj = Session.query(ModeratorPin).get(pin)
        if obj is not None and session.get('username') != obj.username:
            abort(403, 'You are not allowed to view this page.')
            
    def checkAdmin(self, asbool=False):
        """Check if user is really an admin"""
        if (session.get('username')+'@'+session.get('domain')) in aslist(config.get('adminList'), ','):
            if (asbool):
                return True
            return
        elif (asbool):
            return False

        log.warning('User %s tried to acess the admin site without authorization' % session.get('username'))
        abort(403)
