"""Pylons environment configuration"""
import os

from pylons import config

import trioexplorer.lib.app_globals as app_globals
import trioexplorer.lib.helpers
from trioexplorer.config.routing import make_map

import getpass
import pgdb
from beaker.util import verify_directory

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='trioexplorer',
                    template_engine='mako', paths=paths)

    config['routes.map'] = make_map()
    config['pylons.g'] = app_globals.Globals()
    config['pylons.h'] = trioexplorer.lib.helpers

    # Customize templating options via this variable
    tmpl_options = config['buffet.template_options']
    tmpl_options['mako.input_encoding'] = 'utf-8'

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    verify_directory(os.path.join(app_conf['cache_dir'], 'graphs'))

    # This is a Trio admin user login & password check
    if "prompt_password" in app_conf and app_conf["prompt_password"] == "true":
        try:
            if "default_user" in app_conf:
                db = pgdb.connect(database=app_conf["default_user"], user=app_conf["default_user"])
            else:
                db = pgdb.connect()
            db.close()
            print "\nPostgres DBA connection for TrioExplorer: OK\n"
        except Exception, e:
            if "does not exist" in str(e) or "no password supplied" in str(e):
                print
                print e
                print "\nPostgres DBA connection required for TrioExplorer:"
                app_conf["username"] = raw_input("DBA username: ")
                app_conf["password"] = getpass.getpass("    password: ")
                print
                db = pgdb.connect(database=app_conf["username"], user=app_conf["username"], password=app_conf["password"])
                db.close()
            else:
                raise e
