#!/usr/bin/env python
# -*- 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:
    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):
        logger.exception(u"Cannot access configuration file at %r as defined "
                         u"by the %r environment variable.",
                         pootle_settings_filepath, pootle_settings_envvar)
        import sys
        sys.exit(1)


if CONTACT_EMAIL:
    MANAGERS += (('CONTACT', CONTACT_EMAIL),)

if LIVE_TRANSLATION:
    # Look for localization files under PODIRECTORY/pootle
    LOCALE_PATHS = (os.path.join(PODIRECTORY, "pootle"), )
else:
    # Look for localization files under the 'locale' directory
    LOCALE_PATHS = (working_path("locale"), )

from pootle.i18n import override, gettext_live, gettext
from django.utils import translation
from django.utils.translation import trans_real

LANGUAGES = override.find_languages(LOCALE_PATHS[0])

def hijack_translation():
    """Sabotage django's fascist linguistical regime."""
    # Override functions that check if language is known to Django
    translation.check_for_language = lambda lang_code: True
    trans_real.check_for_language = lambda lang_code: True
    translation.get_language_from_request = override.get_language_from_request

    # Override django's inadequate bidi detection
    translation.get_language_bidi = override.get_language_bidi

    if LIVE_TRANSLATION:
        trans_real.translation = override.translation_dummy
        override.override_gettext(gettext_live)
    else:
        # Even when live translation is not enabled we hijack
        # gettext functions to install the safe variable formatting override
        override.override_gettext(gettext)

hijack_translation()


# Setup a tempdir inside the ``PODIRECTORY`` 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(PODIRECTORY, ".tmp")
# Ensure that temp dir exists
if not os.path.exists(tempfile.tempdir):
    os.mkdir(tempfile.tempdir)

# Setup the checkout directory if it doesn't exist
if not os.path.exists(VCS_DIRECTORY):
    os.mkdir(VCS_DIRECTORY)


TEMPLATE_DEBUG = DEBUG
if TEMPLATE_DEBUG:
    TEMPLATE_CONTEXT_PROCESSORS += ("django.core.context_processors.debug",)

if DEBUG:
    TEMPLATE_LOADERS = (
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    )

    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)s %(message)s',
    )
else:
    # We should only enable caching with DEBUG = False
    TEMPLATE_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',
    )
