# Django default settings for passerelle project.

import logging
import os

from django.conf import global_settings

try:
    from logging.handlers import NullHandler
except ImportError:
    # python < 2.7
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass


logging.getLogger('passerelle').addHandler(NullHandler())

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

### Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'please-change-me-with-a-very-long-random-string'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'passerelle.sqlite3',
    }
}

### End of "Quick-start development settings"


# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# mode for newly updated files
FILE_UPLOAD_PERMISSIONS = 0o644

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'passerelle', 'static'),)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = list(global_settings.STATICFILES_FINDERS) + ['gadjo.finders.XStaticFinder']

MIDDLEWARE = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'passerelle.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'passerelle.wsgi.application'

LOCALE_PATHS = (os.path.join(BASE_DIR, 'passerelle', 'locale'),)
LANGUAGE_CODE = 'fr-fr'

# Templates
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'passerelle', 'templates')],
        'APP_DIRS': True,
        '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',
                'django.template.context_processors.request',
            ],
            'builtins': [
                'publik_django_templatetags.publik.templatetags.publik',
            ],
        },
    },
]

INSTALLED_APPS = (
    # system apps
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.postgres',
    # base app
    'passerelle.base',
    'passerelle.address',
    'passerelle.sms',
    # connectors
    'passerelle.apps.actesweb',
    'passerelle.apps.airquality',
    'passerelle.apps.api_entreprise',
    'passerelle.apps.api_particulier',
    'passerelle.apps.arcgis',
    'passerelle.apps.arpege_ecp',
    'passerelle.apps.astech',
    'passerelle.apps.astregs',
    'passerelle.apps.astre_rest',
    'passerelle.apps.atal',
    'passerelle.apps.atos_genesys',
    'passerelle.apps.base_adresse',
    'passerelle.apps.bbb',
    'passerelle.apps.bdp',
    'passerelle.apps.cartads_cs',
    'passerelle.apps.choosit',
    'passerelle.apps.cityweb',
    'passerelle.apps.clicrdv',
    'passerelle.apps.cmis',
    'passerelle.apps.cryptor',
    'passerelle.apps.csvdatasource',
    'passerelle.apps.esabora',
    'passerelle.apps.esirius',
    'passerelle.apps.family',
    'passerelle.apps.feeds',
    'passerelle.apps.filr_rest',
    'passerelle.apps.franceconnect_data',
    'passerelle.apps.gdc',
    'passerelle.apps.gesbac',
    'passerelle.apps.holidays',
    'passerelle.apps.jsondatastore',
    'passerelle.apps.ldap',
    'passerelle.apps.litteralis',
    'passerelle.apps.maelis',
    'passerelle.apps.mdel',
    'passerelle.apps.mdel_ddpacs',
    'passerelle.apps.mobyt',
    'passerelle.apps.okina',
    'passerelle.apps.opendatasoft',
    'passerelle.apps.opengis',
    'passerelle.apps.orange',
    'passerelle.apps.ovh',
    'passerelle.apps.oxyd',
    'passerelle.apps.phonecalls',
    'passerelle.apps.photon',
    'passerelle.apps.plone_restapi',
    'passerelle.apps.proxy',
    'passerelle.apps.sector',
    'passerelle.apps.sfr_dmc',
    'passerelle.apps.signal_arretes',
    'passerelle.apps.sivin',
    'passerelle.apps.smsfactor',
    'passerelle.apps.soap',
    'passerelle.apps.solis',
    'passerelle.apps.twilio',
    'passerelle.apps.vivaticket',
    # backoffice templates and static
    'gadjo',
)

# disable some applications for now
PASSERELLE_APP_BDP_ENABLED = False
PASSERELLE_APP_GDC_ENABLED = False
PASSERELLE_APP_STRASBOURG_EU_ENABLED = False

# mark some apps as legacy
PASSERELLE_APP_CLICRDV_LEGACY = True
PASSERELLE_APP_SOLIS_APA_LEGACY = True

# Authentication settings
try:
    import mellon
except ImportError:
    mellon = None

if mellon is not None:
    INSTALLED_APPS += ('mellon',)
    AUTHENTICATION_BACKENDS = (
        'mellon.backends.SAMLBackend',
        'django.contrib.auth.backends.ModelBackend',
    )

LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_URL = '/logout/'

MELLON_ATTRIBUTE_MAPPING = {
    'email': '{attributes[email][0]}',
    'first_name': '{attributes[first_name][0]}',
    'last_name': '{attributes[last_name][0]}',
}

MELLON_SUPERUSER_MAPPING = {
    'is_superuser': 'true',
}

MELLON_USERNAME_TEMPLATE = '{attributes[name_id_content]}'

MELLON_IDENTITY_PROVIDERS = []

# management command, used to run afterjobs in uwsgi mode,
# usually /usr/bin/passerelle-manage.
PASSERELLE_MANAGE_COMMAND = None

# REQUESTS_PROXIES that can be used by requests methods
# see http://docs.python-requests.org/en/latest/user/advanced/#proxies
REQUESTS_PROXIES = None

# timeout used in python-requests call, in seconds
# we use 25s by default: timeout just before web server, which is usually 30s,
# and before clients, which usually use 28s (see w.c.s. or Combo)
REQUESTS_TIMEOUT = 25

# Retry all requests
# See: https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.Retry
# Example:
# REQUESTS_MAX_RETRIES = {
#     'total': 3,
#     'backoff_factor': 0.1,
# }
REQUESTS_MAX_RETRIES = {}

# Connectors settings - extra settings for connectors
#
# CONNECTORS_SETTINGS = {
#   "cmis/test": {
#     "requests_substitutions": [
#       {
#         'url': 'https://service.example.com/api/',
#         'search': 'http://service.example.internal/software/api/',
#         'replace': 'https://service.example.com/api/'
#       }
#     ]
#   ]
# ]
#
# * requests_substitutions:
#   Apply substitutions to HTTP responses obtained through self.requests
#   search is a python regular expression for re.sub(), and replace the replacement string.
#   The 'url' key is optional, if absent the replacement is done on all URLs.
CONNECTORS_SETTINGS = {}

# List of authorized content-types, as regular expressions, for substitutions
REQUESTS_SUBSTITUTIONS_CONTENT_TYPES = [r'text/.*', r'application/(.*\+)?json', r'application/(.*\+)?xml']

# Passerelle can receive big requests (for example base64 encoded files)
DATA_UPLOAD_MAX_MEMORY_SIZE = 100 * 1024 * 1024

SITE_BASE_URL = 'http://localhost'

# List of passerelle.utils.Request response Content-Type to log
LOGGED_CONTENT_TYPES_MESSAGES = [r'text/.*', r'application/(.*\+)?json', r'application/(.*\+)?xml']

# Max size of the response to log
LOGGED_RESPONSES_MAX_SIZE = 5000

# Max size of the request to log
LOGGED_REQUESTS_MAX_SIZE = 5000

# Number of days to keep logs
LOG_RETENTION_DAYS = 7


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
            'propagate': True,
        },
        'passerelle.resource': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
            'propagate': True,
        },
    },
}

local_settings_file = os.environ.get(
    'PASSERELLE_SETTINGS_FILE', os.path.join(os.path.dirname(__file__), 'local_settings.py')
)
if os.path.exists(local_settings_file):
    with open(local_settings_file) as f:
        exec(f.read())
