"""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 template_engine == 'mako'}}
from pylons.error import handle_mako_error
{{endif}}
{{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}}
from {{package}}.model import init_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'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8', default_filters=['escape'],
        imports=['from webhelpers.html import escape'])
    {{elif template_engine == 'genshi'}}

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

    # 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 database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    init_model(engine)
    {{endif}}

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
