"""Pylons environment configuration"""
import os


{{if template_engine == 'mako'}}
from mako.lookup import TemplateLookup
{{elif template_engine == 'genshi'}}
from genshi.template import TemplateLoader
{{elif template_engine == 'jinja2'}}
from jinja2 import ChoiceLoader, Environment, FileSystemLoader
{{endif}}
from pylons import config
{{if sqlalchemy}}
from sqlalchemy import engine_from_config
{{endif}}

import {{package}}.lib.app_globals as app_globals
import {{package}}.lib.helpers
from {{package}}.config.routing import make_map
{{if sqlalchemy}}
import {{package}}.model as model
{{endif}}

def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='{{package}}', paths=paths)

    config['routes.map'] = make_map()
    config['pylons.app_globals'] = app_globals.Globals()
    config['pylons.h'] = {{package}}.lib.helpers
    {{if template_engine == 'mako'}}

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8', output_encoding='utf-8',
        imports=['from webhelpers.html import escape'],
        default_filters=['escape'])
    {{elif template_engine == 'genshi'}}

    # Create the Genshi TemplateLoader
    config['pylons.app_globals'].genshi_loader = TemplateLoader(
        paths['templates'], auto_reload=True)
    {{elif template_engine == 'jinja'}}

    # Create the Jinja2 Environment
    config['pylons.app_globals'].jinja2_env = Environment(loader=ChoiceLoader(
            [FileSystemLoader(path) for path in paths['templates']]))
    # Jinja2's unable to request c's attributes without strict_c
    config['pylons.strict_c'] = True
    {{endif}}
    {{if sqlalchemy}}
    # Setup the SQLAlchemy^W Elixir database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    if model.elixir.options_defaults.get('autoload'):
        # Reflected tables
        model.elixir.bind = engine
        model.metadata.bind = engine
        model.elixir.setup_all()
    else:
        # Non-reflected tables
        model.init_model(engine)
    {{endif}}
    
    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
