# -*- coding: utf-8 -*-
"""The base Controller API

Provides the BaseController class for subclassing.
"""
from pylons.controllers import WSGIController
{{if template_engine in ('genshi', 'jinja2', 'mako')}}
from pylons.templating import render_{{template_engine}} as render
{{endif}}

from pylons import config, session, request, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from {{package}} import model as model

from pylons import config
from couchdb import Database
from {{package}}.model.user import User

class BaseController(WSGIController):

    def _setup(self):
        """Do basic request setup"""
        if session.get('logged_in', False):
            user = User.load(self.db, session.get('user_id'))
            if not user or user.session_id != session.id:
                user = None
                session['logged_in'] = False
                session.delete()
                session.save()
        else:
            user = None
    
    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']

        # Insert any code to be run per request here.

        c.db = self.db = Database(config['couchdb_uri'])
        self._setup()

        return WSGIController.__call__(self, environ, start_response)
    

