# -*- 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:
    logger = logging.getLogger('pootle.settings')

    # Set a handler to avoid the "No handlers could be found" error to happen.
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    # Set the appropiate logging level
    logger.setLevel(logging.DEBUG if DEBUG else logging.INFO)

    try:
        logger.info(u"Loading custom settings from %r...",
                    pootle_settings_filepath)
        execfile(os.path.abspath(pootle_settings_filepath))
    except (IOError, OSError), e:
        logger.error(u"Cannot access configuration file at %r as defined by "
                     u"the %r environment variable:\n%s",
                     pootle_settings_filepath, pootle_settings_envvar, e)
        import sys
        sys.exit(1)

# 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)
