# -*- coding: utf-8 -*-

"""Setup things that depend on other settings."""

import logging


# Load custom settings if any have been defined
pootle_settings_envvar = 'POOTLE_SETTINGS'
pootle_settings_filepath = os.environ.get(pootle_settings_envvar, None)

if pootle_settings_filepath is not None:
    for custom_filepath in pootle_settings_filepath.split(":"):
        logger = logging.getLogger(__name__)
        abs_settings_path = os.path.abspath(custom_filepath)
	config_exists = (
            os.path.exists(abs_settings_path)
            and os.path.isfile(abs_settings_path))
	if config_exists:
            logger.debug(
	        u"Loading custom settings from %r...",
                custom_filepath)
	    execfile(abs_settings_path)

# Look for localization files under the 'locale' directory
LOCALE_PATHS = (working_path("locale"), )

from pootle.i18n import override
LANGUAGES = override.find_languages(LOCALE_PATHS[0])
override.hijack_translation()


# Setup a tempdir inside the ``POOTLE_TRANSLATION_DIRECTORY`` hierarchy, this
# way we have reasonable guarantee that temp files will be created on the same
# filesystem as translation files (required for save operations).
import tempfile
tempfile.tempdir = os.path.join(POOTLE_TRANSLATION_DIRECTORY, ".tmp")
# Ensure that temp dir exists
if not os.path.exists(tempfile.tempdir):
    os.mkdir(tempfile.tempdir)


if DEBUG:
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)s %(message)s',
    )
else:
    TEMPLATES[0]['OPTIONS']['loaders'] = (
        ('django.template.loaders.cached.Loader', [
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
        ]),
    )

    # Will log only CRITICAL errors to the console
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s %(levelname)s %(message)s',
    )


# Update LOGGING with forward referenced POOTLE_LOG_DIRECTORY
for handler in LOGGING['handlers']:
    if 'filename' in LOGGING['handlers'][handler]:
        LOGGING['handlers'][handler]['filename'] = \
            LOGGING['handlers'][handler]['filename'].replace("%POOTLE_LOG_DIRECTORY%",
                                                             POOTLE_LOG_DIRECTORY)
