""" This module holds the base settings of the ``mtp`` app. """

import os
import string
import sys
from urllib.parse import urljoin

from django.contrib.messages import constants as message_constants
from django.core.urlresolvers import reverse_lazy

from celery.schedules import crontab

from .. import __version__

from .utils import get_env_variable, get_bool_env_variable


SECRET_KEY = get_env_variable('MTP_SECRET_KEY')

ADMINS = [
    (get_env_variable('MTP_ADMIN_NAME'), get_env_variable('MTP_ADMIN_EMAIL')),
]
MANAGERS = ADMINS

DATABASES = {
    'default': {
        # Important, to manage "deferrable" constraints for "sort_order" unique constraints.
        'ENGINE': 'mtp.mtp_db_backend',
        'NAME': get_env_variable('MTP_DATABASE_NAME'),
        'USER': get_env_variable('MTP_DATABASE_USER'),
        'PASSWORD': get_env_variable('MTP_DATABASE_PASSWORD'),
        'HOST': get_env_variable('MTP_DATABASE_HOST'),
        'PORT': get_env_variable('MTP_DATABASE_PORT'),
        'ATOMIC_REQUESTS': True,
        'TEST': {
            'NAME': get_env_variable(
                'MTP_TEST_DATABASE_NAME',
                default='test_' + get_env_variable('MTP_DATABASE_NAME'),
            )
        }
    }
}

INSTANCE_NAME = get_env_variable('MTP_INSTANCE_NAME', default='')

SITE_ID = 1

TIME_ZONE = 'Europe/Paris'

LANGUAGE_CODE = 'en'
DEFAULT_NATURAL_LANGUAGE = 'en'

LANGUAGES = [
    ('fr', "Français"),
    ('fr-BE', "Français (Belgium)"),
    ('fr-CH', "Français (Swiss)"),
    ('en', "English"),
    ('en-GB', "English (Britain)"),
    ('de', "Deutsch"),
    ('de-CH', "Deutsch (Swiss)"),
    ('de-AT', "Deutsch (Austria)"),
    ('es', "Español"),
    ('it', "Italiano"),
    ('it-CH', "Italiano (Swiss)"),
    ('pt', "Portuguese"),
    ('nl', "Nederlands"),
    ('nl-BE', "Dutch (Belgium)"),
    ('pl', "Polski"),
    ('cs', "Czech"),
    ('sk', "Slovak"),
    ('da', "Dansk"),
    ('sv', "Svenska"),
    ('no', "Norsk"),
    ('fi', "Suomi"),
    ('hu', "Magyar"),
    ('bg', "Bulgarian"),
    ('el', "Ελληνικά"),
    ('ru', "Русский"),
    ('ja', "日本語"),
]

USE_I18N = True
USE_L10N = True
USE_TZ = True

SETTINGS_ROOT = os.path.dirname(os.path.realpath(__file__))
PROJECT_ROOT = os.path.dirname(SETTINGS_ROOT)
APPS_ROOT = os.path.join(PROJECT_ROOT, 'apps')
MEDIA_ROOT = get_env_variable('MTP_MEDIA_ROOT')  # different per-instance
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
TEMPLATES_ROOT = os.path.join(PROJECT_ROOT, 'templates')
CUSTOM_ROOT = os.path.join(PROJECT_ROOT, 'custom')
LOCALE_PATHS = [
    os.path.join(MEDIA_ROOT, 'custom_locale'),  # Custom translation (client specific)
    os.path.join(PROJECT_ROOT, 'locale'),
]

ALLOWED_HOSTS = ['*']

ROOT_URLCONF = 'mtp.urls'
APPEND_SLASH = True

MEDIA_URL = '/media/'
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(PROJECT_ROOT, 'assets'),
]
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

ADMIN_MEDIA_PREFIX = '/static/admin/'

WSGI_APPLICATION = 'mtp.wsgi.application'

INSTALLED_APPS = [

    'flat',

    # Django apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'django.forms',

    # Third-party apps
    'autofixture',
    'bootstrap3',
    'constance',
    'constance.backends.database',
    'django_extensions',
    'django_lockable',
    'django_markdown',
    'django_select2',
    'easy_thumbnails',
    'form_utils',
    'oauth2_provider',
    'orderable',
    'pinax.notifications',
    'rest_framework',
    'rest_framework_swagger',
    'waffle',

    # MTP discrete apps (not related to mtp content)
    'mtp.discrete_apps.duplicable',
    'mtp.discrete_apps.versionable',

    # MTP apps
    'mtp.apps.accounts',
    'mtp.apps.api',
    'mtp.apps.assessments',
    'mtp.apps.brainstormers',
    'mtp.apps.challenges',
    'mtp.apps.cms',
    'mtp.apps.common',
    'mtp.apps.documents',
    'mtp.apps.evaluations',
    'mtp.apps.eventlog',
    'mtp.apps.ideas',
    'mtp.apps.import_export',
    'mtp.apps.likes',
    'mtp.apps.media',
    'mtp.apps.metaplans',
    'mtp.apps.pdf_reporting',
    'mtp.apps.questionnaires',
    'mtp.apps.photostories',
    'mtp.apps.reveal',
    'mtp.apps.roleplays',
    'mtp.apps.stats',
    'mtp.apps.surveys',
    'mtp.apps.sync',
    'mtp.apps.tasks',
    'mtp.apps.themes',
    'mtp.apps.trainings',
    'mtp.apps.translation',
    'mtp.apps.workshops',

    # Saba connector
    # installed for everybody, but enabled through constance config
    'mtp.discrete_apps.saba',
]

SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
AUTH_USER_MODEL = 'accounts.MTPUser'
PASSWORD_HASHERS = [
    'mtp.hashers.MTPPasswordHasher',
]
ROOT_URL = reverse_lazy('cms:index')
LOGIN_URL = reverse_lazy('login')
LOGIN_REDIRECT_URL = ROOT_URL

FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'waffle.middleware.WaffleMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'mtp.apps.accounts.middleware.PasswordExpiryMiddleware',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
    'mtp.apps.accounts.middleware.NonDeletedOrDeactivatedUserMiddleware',
]

# Authentication settings
# -----------------------

AUTHENTICATION_BACKENDS = [
    'oauth2_provider.backends.OAuth2Backend',
    'django.contrib.auth.backends.ModelBackend',
]

_TEMPLATE_DIRS = []

# If we are running a customized instance, its specific templates
# should be found before the standard MTP ones.
if INSTANCE_NAME:
    INSTANCE_PATH = os.path.join(CUSTOM_ROOT, INSTANCE_NAME)
    _TEMPLATE_DIRS.extend([
        os.path.join(INSTANCE_PATH, 'templates'),
        os.path.join(INSTANCE_PATH, 'templates', 'cms')
    ])

_TEMPLATE_DIRS.extend([
    TEMPLATES_ROOT,
    os.path.join(TEMPLATES_ROOT, 'cms'),

    # This is a trick to allow templates in the /custom/ tree to
    # both override and extend those in the regular /templates/ one.
    # See: https://code.djangoproject.com/wiki/ExtendingTemplates
    PROJECT_ROOT,
])

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'DIRS': _TEMPLATE_DIRS,
        'OPTIONS': {
            'context_processors': [
                "django.contrib.auth.context_processors.auth",
                "django.template.context_processors.debug",
                "django.template.context_processors.i18n",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
                "django.template.context_processors.tz",
                "django.contrib.messages.context_processors.messages",
                "mtp.apps.common.context_processors.instance_version",
                "mtp.apps.themes.context_processors.theme",
            ]
        }
    },
]


# Redis-related settings (cache, sessions, limpyd)
# ------------------------------------------------

REDIS_HOST = get_env_variable('MTP_REDIS_HOST', default='localhost')
REDIS_PORT = int(get_env_variable('MTP_REDIS_PORT', default=6379))


# We use a Redis database for caching purposes, thanks to:
#  https://github.com/sebleier/django-redis-cache

if get_bool_env_variable('MTP_USE_REDIS_FOR_CACHE', default=True):
    CACHE_REDIS_HOST = REDIS_HOST
    CACHE_REDIS_PORT = REDIS_PORT
    CACHE_REDIS_DB = int(get_env_variable('MTP_REDIS_CACHE_DB', default=0))
    CACHES = {
        'default': {
            'BACKEND': 'redis_cache.RedisCache',
            'LOCATION': '%s:%d' % (CACHE_REDIS_HOST, CACHE_REDIS_PORT),
            'OPTIONS': {
                'DB': CACHE_REDIS_DB,
                'PARSER_CLASS': 'redis.connection.HiredisParser',
                'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool',
                'CONNECTION_POOL_CLASS_KWARGS': {
                    'max_connections': 50,
                    'timeout': 20,
                }
            },
        },
    }

# We also use a Redis database to manage user sessions, thanks to:
#  https://github.com/martinrusev/django-redis-sessions

if get_bool_env_variable('MTP_USE_REDIS_FOR_SESSIONS', default=True):
    SESSION_ENGINE = 'redis_sessions.session'
    SESSION_REDIS_HOST = REDIS_HOST
    SESSION_REDIS_PORT = REDIS_PORT
    SESSION_REDIS_DB = int(get_env_variable('MTP_REDIS_SESSIONS_DB', default=1))

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
MESSAGE_TAGS = {message_constants.ERROR: 'danger'}

# We also use a Redis database for miscellaneous application purposes,
# thanks to our very own @twidi's django-limpyd app:
#  https://github.com/yohanboniface/redis-limpyd

LIMPYD_REDIS = {
    'host': REDIS_HOST,
    'port': REDIS_PORT,
    'db': int(get_env_variable('MTP_REDIS_LIMPYD_DB', default=2)),
}

# We also use a Redis database as a broker for Celery
# http://docs.celeryproject.org/en/latest/getting-started/brokers/redis.html#broker-redis

CELERY_REDIS_LOCATION = '%s:%d' % (REDIS_HOST, REDIS_PORT)
CELERY_REDIS_DB = int(get_env_variable('MTP_REDIS_CELERY_DB', default=3))
CELERY_RESULT_BACKEND = 'redis://%s/%d' % (CELERY_REDIS_LOCATION, CELERY_REDIS_DB)
BROKER_URL = 'redis://%s/%d' % (CELERY_REDIS_LOCATION, CELERY_REDIS_DB)


# Deployment-related settings
# ---------------------------

# This has an effect on the file download method.
# See apps/documents/views.py for details.
USE_REVERSE_PROXY = True


# Logging-related settings
# ------------------------

# Tell sentry to not Hijack the root logger so we can use our own
# https://stackoverflow.com/questions/9810104/sentry-raven-and-django-celery
CELERYD_HIJACK_ROOT_LOGGER = False

LOGGING_ROOT = get_env_variable('MTP_LOGGING_ROOT')

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'simple': {'format': '%(levelname)s %(message)s'},
        'verbose': {
            'format': (
                '%(asctime)s [%(levelname)s] ' +
                'pathname=%(pathname)s lineno=%(lineno)s ' +
                'funcname=%(funcName)s %(message)s'
            ),
            'datefmt': '%Y-%m-%d %H:%M:%S',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
        'logfile_django': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'formatter': 'verbose',
            'filename': os.path.join(LOGGING_ROOT, 'django.log'),
        },
        'logfile_django_sql': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'formatter': 'verbose',
            'filename': os.path.join(LOGGING_ROOT, 'django_sql.log'),
        },
        'logfile_celery': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'formatter': 'verbose',
            'filename': os.path.join(LOGGING_ROOT, 'celery.log'),
        },
        'sentry': {
            'level': 'ERROR',
            'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
            'formatter': 'verbose',
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        '': {
            'level': 'DEBUG',
            'handlers': ['console', 'sentry'],
            },
        'root': {
            'level': 'DEBUG',
            'handlers': ['console'],
        },
        'django': {
            'level': 'ERROR',
            'handlers': ['logfile_django'],
        },
        'django.db': {
            'level': 'ERROR',
            'handlers': ['logfile_django_sql'],
        },
        'django.request': {
            'level': 'ERROR',
            'handlers': ['console'],
        },
        'celery': {
            'level': 'ERROR',
            'handlers': ['logfile_celery', 'sentry'],
        },
        'mtp': {
            'level': 'ERROR',
            'handlers': ['sentry'],
        },
    },
}

# Sentry configuration.
if get_bool_env_variable('MTP_USE_SENTRY'):
    INSTALLED_APPS = INSTALLED_APPS + ['raven.contrib.django.raven_compat']
    RAVEN_CONFIG = {
        'dsn': get_env_variable('MTP_SENTRY_DSN'),
        'release': __version__,
    }


# Email-related settings
# ----------------------

EMAIL_BACKEND = 'django.core.mail.backends.%s.EmailBackend' % get_env_variable(
    'MTP_EMAIL_BACKEND', default='smtp'
)
EMAIL_HOST = get_env_variable('MTP_EMAIL_HOST')
EMAIL_PORT = int(get_env_variable('MTP_EMAIL_PORT'))
EMAIL_HOST_USER = get_env_variable('MTP_EMAIL_USER')
EMAIL_HOST_PASSWORD = get_env_variable('MTP_EMAIL_PASSWORD')
EMAIL_USE_TLS = get_bool_env_variable('MTP_EMAIL_USE_TLS')

EMAIL_SENDER = get_env_variable('MTP_EMAIL_SENDER')
EMAIL_ENABLED = get_bool_env_variable('MTP_EMAIL_ENABLED', default=False)
DEFAULT_FROM_EMAIL = get_env_variable(
    'MTP_DEFAULT_FROM_EMAIL',
    default='Magency <no-reply@magency.me>'
)

# System check settings
# ---------------------

SILENCED_SYSTEM_CHECKS = [

    # Do not warn us about unit tests discovery
    '1_6.W001',
]


# MTP-specific settings
# ---------------------

MHR_VERSION = get_env_variable('MTP_MHR_VERSION', default='NC')

INSTANCE_IS_SLAVE = get_bool_env_variable('MTP_INSTANCE_IS_SLAVE')
INSTANCE_IS_MASTER = not INSTANCE_IS_SLAVE

MASTER_INSTANCE_HOST = get_env_variable('MTP_MASTER_INSTANCE_HOST')
CURRENT_INSTANCE_HOST = get_env_variable('MTP_CURRENT_INSTANCE_HOST')
USE_SECURE_PROTOCOL_FOR_MASTER = get_bool_env_variable(
    'MTP_USE_SECURE_PROTOCOL_FOR_MASTER', default=False
)
USE_SECURE_PROTOCOL_FOR_CURRENT = get_bool_env_variable(
    'MTP_USE_SECURE_PROTOCOL_FOR_CURRENT', default=False
)
HTTPS = 'https://'
HTTP = 'http://'
MASTER_INSTANCE_URL = (HTTPS if USE_SECURE_PROTOCOL_FOR_MASTER else HTTP) + MASTER_INSTANCE_HOST
CURRENT_INSTANCE_URL = (HTTPS if USE_SECURE_PROTOCOL_FOR_CURRENT else HTTP) + CURRENT_INSTANCE_HOST

CLIENT_NAME = get_env_variable('MTP_CLIENT_NAME')

# The websocket message broker is used by the mhr clients (iOS and HTML)
MESSAGE_BROKER_WEBSOCKET_HOST = get_env_variable('MTP_MESSAGE_BROKER_WEBSOCKET_HOST')
MESSAGE_BROKER_WEBSOCKET_PORT = int(get_env_variable('MTP_MESSAGE_BROKER_WEBSOCKET_PORT'))

# The http message broker is used by the mhr server
MESSAGE_BROKER_HTTP_HOST = get_env_variable('MTP_MESSAGE_BROKER_HTTP_HOST')
MESSAGE_BROKER_HTTP_PORT = int(get_env_variable('MTP_MESSAGE_BROKER_HTTP_PORT'))

MESSAGE_BROKER_PUBLICATION_URL = '/pub/'

IPA_STORE_URL = get_env_variable('MTP_IPA_STORE_URL', default='https://store.magency.fr/')
LAST_IPA_VERSION_DETAIL_URL = urljoin(IPA_STORE_URL, 'app/Engage/%s/detail' % CLIENT_NAME)
LAST_IPA_VERSION_PLIST_URL = urljoin(IPA_STORE_URL, 'app/Engage/%s/plist' % CLIENT_NAME)
LAST_IPA_VERSION_ITMS_URL = 'itms-services://?action=download-manifest&url=%s' % (
    LAST_IPA_VERSION_PLIST_URL
)

EXPORTS_ROOT = get_env_variable('MTP_EXPORTS_ROOT')  # different per-instance
SCRIPTS_ROOT = os.path.join(PROJECT_ROOT, 'scripts')

# Set this to True to enforce extra checks and password expiration.
PASSWORD_EXTRA_SECURITY = get_bool_env_variable(
    'MTP_PASSWORD_EXTRA_SECURITY', default=False
)
# Expressed in days, only enforced if PASSWORD_EXTRA_SECURITY is set to True.
PASSWORD_TTL = int(get_env_variable('MTP_PASSWORD_TTL', default=90))

ANNOTATIONS_ROOT = get_env_variable('MTP_ANNOTATIONS_ROOT')  # different per-instance
ANNOTATIONS_SCRIPT_ROOT = os.path.join(ANNOTATIONS_ROOT, 'scripts')
ANNOTATIONS_DATA_ROOT = os.path.join(MEDIA_ROOT, 'pdfgen')
ANNOTATIONS_DATA_URL = os.path.join(MEDIA_URL, 'pdfgen')
ANNOTATIONS_SIZE = 24  # TODO: magic number?

PGDUMP_SAVE_ROOT = os.path.join(MEDIA_ROOT, 'pgdump')
REV_SAVE_ROOT = os.path.join(MEDIA_ROOT, 'revision')
UPLOAD_ROOT = os.path.join(MEDIA_ROOT, 'upload')

DEFAULT_PREVIEW_HASH = 'd8a365ee42e571b7915f9b5109829c9a'
DEFAULT_PREVIEW_UUID = '12345678-1234-1234-1234-123456789123'
DEFAULT_PREVIEW_FILENAME = 'no-preview.png'
DEFAULT_PREVIEW_URL = os.path.join(MEDIA_URL, DEFAULT_PREVIEW_FILENAME)

EMPTY_FILE_HASH = 'd41d8cd98f00b204e9800998ecf8427e'

UPLOAD_TO = {
    'DownloadableFile': 'image_downloadable',
    'ClientVersion': 'app_update',
    'ServerVersion': 'server_update',
    'Document': 'documents',
    'Exercise': 'evaluation/exercice',
    'Avatar': 'avatar',
    'BrainstormerActivity': 'metaplans/activities',
    'Training': 'training',
    'PdfMedia': 'media_app/pdf',
    'VideoMedia': 'media_app/video',
    'ImageChoicesQuestion': 'questionnaires/imagechoicesquestion',
}

# If set to ``True``, the surveys stats will be updated each time an answer is saved.
# If set to ``False``, this will not be the case and this must be done via a cron or something else.
SURVEYS_AUTO_COMPUTE_STATS = get_bool_env_variable('MTP_SURVEYS_AUTO_COMPUTE_STATS', default=False)

# Theme settings
# --------------

# TODO: Maybe these should go in a separate file? themes.py?
# Or maybe these should just be deprecated...

THEME_COLOR_FIRST = '#823481'
THEME_COLOR_SECOND = '#d7d7d7'
THEME_COLOR_ITEM = '#ffffff'
THEME_COLOR_SELECTED_ITEM = '#823481'
THEME_COLOR_TEXT_ITEM = '#686868'
THEME_COLOR_TEXT_SELECTED_ITEM = '#ffffff'
THEME_COLOR_TEXT_QUIZZ = '#ffffff'
THEME_BACKGROUND_COLOR = '#cccccc'
THEME_BACKGROUND_COLOR_DIFFUSION = '#D6D6D6'
THEME_BACKGROUND_IMAGE = ''
THEME_BACKGROUND_IMAGE_DIFFUSION = ''
THEME_HEADER_IMAGE = 'default/header.png'
THEME_HOME_DIFFUSION_IMAGE = 'default/home_diffusion.png'
THEME_GRAY_COLOR = '#BDBDBD'
SMALL_CLIENT_LOGO = os.path.join(STATIC_ROOT, 'small_client_logo.png')
NORMAL_CLIENT_LOGO = os.path.join(STATIC_ROOT, 'normal_client_logo.png')
HUGE_CLIENT_LOGO = os.path.join(STATIC_ROOT, 'huge_client_logo.png')

TRAINING_DEFAULT_IMAGE = 'training/training.png'

DEFAULT_TOKEN_PATTERNS = get_env_variable(
    'MTP_DEFAULT_TOKEN_PATTERNS',
    default=string.ascii_uppercase
)

# See the ``is_live`` method in ``mtp.apps.training.models.TrainingSession``
SESSION_TRAINER_TIMEOUT = 60 * 30  # 30 minutes

SWAGGER_SETTINGS = {
    'exclude_namespaces': ['api'],
    'api_version': '2.0',
    'info': {
        'contact': 'mtp@magency.fr',
        'title': 'MTP API Documentation',
    },
}

# Notifications settings
# ----------------------

PINAX_NOTIFICATIONS_BACKENDS = [
    ("email", "mtp.apps.common.notifications.backends.email.MultipartEmailBackend"),
]

# django_select2 settings
# -----------------------

SELECT2_BOOTSTRAP = True
AUTO_RENDER_SELECT2_STATICS = False
SELECT2_CACHE_BACKEND = 'default'
SELECT2_JS = STATIC_URL + 'select2/js/select2-4.0.3.min.js'
SELECT2_CSS = STATIC_URL + 'select2/css/select2-4.0.3.min.css'

# Celery Beat sheduled tasks
# --------------------------

CELERYBEAT_SCHEDULE = {}

# Settings for the "close_outdated_training_sessions" task
CELERYBEAT_SCHEDULE['close-outdated-training-sessions-at-midnight'] = {
    'task': 'mtp.apps.trainings.tasks.close_outdated_training_sessions',
    'schedule': crontab(minute=0, hour=0),  # Daily, at midnight
}

# Settings for the rest framework
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework.filters.DjangoFilterBackend',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'mtp.apps.api.renderers.BrowsableAPIRendererWithoutForms',
    ),
    'DEFAULT_METADATA_CLASS': 'mtp.apps.api.metadata.SimpleMetadataWithoutRelatedFieldChoices',
    'EXCEPTION_HANDLER': 'mtp.apps.common.drf.exception_handler',
}

# Load the ReportLab Plus license (expires on 02/05/2017)
# --------------------------

sys.path.append(
    os.path.join(APPS_ROOT, 'pdf_reporting/license')
)

# Necessary to use HTTPS with NGINX
# https://docs.djangoproject.com/en/1.9/ref/settings/#secure-proxy-ssl-header
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Default Magency Superuser
# -------------------------

MAGENCY_ADMIN_USERNAME = get_env_variable('MTP_MAGENCY_ADMIN_USERNAME')
MAGENCY_ADMIN_PASSWORD = get_env_variable('MTP_MAGENCY_ADMIN_PASSWORD')

# OAuth2 Provider settings
# -----------------------
OAUTH2_PROVIDER = {
    'OAUTH2_VALIDATOR_CLASS': 'mtp.apps.api.oauth2_validators.MTPOAuth2Validator'
}


# Default OAuth Application
# -------------------------

OAUTH_APPLICATION_NAME = get_env_variable('MTP_OAUTH_APPLICATION_NAME')
OAUTH_APPLICATION_CLIENT_ID = get_env_variable('MTP_OAUTH_APPLICATION_CLIENT_ID')
OAUTH_APPLICATION_CLIENT_SECRET = get_env_variable('MTP_OAUTH_APPLICATION_CLIENT_SECRET')

# CAST OAuth Application
# ----------------------

# Theses should be env variables, but since Magency Deploy cannot update itself,
# We set them like this for the time being
OAUTH_CAST_APPLICATION_NAME = 'Magency Cast'
OAUTH_CAST_APPLICATION_CLIENT_ID = 'wrRaIIh4GlJX7zYUWEwItpEsgQYJbCEzIGPf4jU8'
OAUTH_CAST_APPLICATION_CLIENT_SECRET = '6yAYPiwkcSzuokmhIiaKj1O9QmoVvQiRs5eJoQlGOrU' \
                                       'N1xkKSVQCZIKEPItQGBjXYf5xlKd43ZBIwozCdsPQc1' \
                                       'SYxKZpetDB7LquhYWf49SjZeoZvkFlNm8Bcp3PL9Vy'

# Rosetta settings
# ----------------------------

if get_bool_env_variable('MTP_ENABLE_ROSETTA', default=False):
    INSTALLED_APPS.append('rosetta')
    ROSETTA_MESSAGES_PER_PAGE = 30
    ROSETTA_ENABLE_REFLANG = True
    ROSETTA_POFILENAMES = ('django.po', 'client.po')

# Sync settings
# -------------

SYNC_ZIP_PASSWORD = get_env_variable('MTP_SYNC_ZIP_PASSWORD')
SYNC_HISTORY_PATH = get_env_variable('MTP_SYNC_HISTORY_PATH')

# Django-constance settings
# -------------------------

CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend'
CONSTANCE_DATABASE_CACHE_BACKEND = 'default'
CONSTANCE_CONFIG = {
    # - begin saba -
    'SABA_USERS_IMPORT_OFFSET': (
        10,
        'The number of rows to skip in the Saba users import file',
    ),
    'SABA_COURSES_IMPORT_OFFSET': (
        6,
        'The number of rows to skip in the Saba courses import file',
    ),
    'SABA_ENABLED': (
        False,
        'Global flag to enable the Saba LMS connector',
    ),
    'SABA_API_BASE_URL': (
        '',
        'The URL of the Saba instance we want to send assessments results to',
    ),
    'SABA_API_USERNAME': (
        '',
        'The username with which to connect to the Saba API',
    ),
    'SABA_API_PASSWORD': (
        '',
        'The password with which to connect to the Saba API',
    ),
    'SABA_API_USERNAME_INTERNAL_ID': (
        '',
        'The Saba internal id of the API user defined at SABA_API_USERNAME',
    ),
    'SABA_RECAP_EMAIL_RECIPIENTS': (
        '',
        'A list of user accounts, separated by commas, that will receive a copy of the sync email',
    ),
    'SABA_SYNCHRO_ENABLED': (
        False,
        'If enabled, it will run the cron for sending assessments results to Saba every night',
    ),
    'SABA_IMPORT_USERS_FILE_PATH': (
        os.path.join(UPLOAD_ROOT, 'saba_users.csv'),
        'The file path of the file containing the users we want to import from SABA'
    ),
    # - end saba -
    'AUTO_CLOSE_SESSIONS_ACTIVATE': (
        True,
        'Activate the auto-close of the training sessions',
    ),
    'AUTO_CLOSE_SESSIONS_GRACE_PERIOD_DAYS': (
        4,
        'The number of days a training session is auto-closed after',
    ),
    'IMAGES_FROM_PDF_ACTIVATE': (
        True,
        'Do we want to generate images from the uploaded pdf ?'
    ),
    'IMAGES_FROM_PDF_RESOLUTION': (
        150,
        'The resolution of the images extracted from the pdf'
    ),
}

# Saba cron tasks
# They won't be executed if SABA_SYNCHRO_ENABLED is not True
CELERYBEAT_SCHEDULE['sync-assessments-to-saba'] = {
    'task': 'mtp.discrete_apps.saba.tasks.sync_assessments_to_saba',
    'schedule': crontab(minute=0, hour=1),  # Daily, at 1AM
}
CELERYBEAT_SCHEDULE['send-saba-recap-email'] = {
    'task': 'mtp.discrete_apps.saba.tasks.send_saba_recap_email',
    'schedule': crontab(minute=0, hour=7),  # Daily, at 7AM
}

# This won't be executed if SABA_ENABLED is not True
CELERYBEAT_SCHEDULE['import_users_from_saba'] = {
    'task': 'mtp.discrete_apps.saba.tasks.import_users_from_saba',
    'schedule': crontab(minute=0, hour=1),  # Daily, at 1AM
}

# Potential duplicate users finder cron task
CELERYBEAT_SCHEDULE['find-potential-duplicate-users'] = {
    'task': 'mtp.apps.accounts.tasks.find_potential_duplicate_users',
    'schedule': crontab(minute=0, hour=4, day_of_week='sun')  # Every sunday, at 4AM
}

LOGMYASS_HTTP_URL = get_env_variable('MTP_LOGMYASS_HTTP_URL', default='')
LOGMYASS_HTTP_PORT = get_env_variable('MTP_LOGMYASS_HTTP_PORT', default='')
LOGMYASS_WEBSOCKET_URL = get_env_variable('MTP_LOGMYASS_WEBSOCKET_URL', default='')
LOGMYASS_WEBSOCKET_PORT = get_env_variable('MTP_LOGMYASS_WEBSOCKET_PORT', default='')


# Easy thumbnails settings
THUMBNAIL_ALIASES = {
    'accounts.Avatar.img': {
        'reveal_small': {
            'size': (128, 128),
            'crop': False,
            'quality': 95
        },
        'reveal_large': {
            'size': (256, 256),
            'crop': False,
            'quality': 95
        }
    },
    'themes.Theme.reveal_logo': {
        'reveal': {
            'size': (128, 128),
            'crop': False,
            'quality': 95
        }
    }
}
THUMBNAIL_BASEDIR = 'thumbnails'
