"""
Django settings for appel_crises project.

Generated by 'django-admin startproject' using Django 3.0.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os

import getconf
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

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

config = getconf.ConfigGetter(
    'appel_crises',
    ['/etc/appel_crises/*.ini', os.path.join(BASE_DIR, 'local_settings.ini')],
)

APPMODE = config.getstr('app.mode', 'dev')
assert APPMODE in ('dev', 'dist', 'prod'), "Invalid application mode %s" % APPMODE

if APPMODE in ('dev', 'dist'):
    _default_secret_key = 'Dev only!!'
else:
    _default_secret_key = ''

SECRET_KEY = config.getstr('app.secret_key', _default_secret_key)

DEBUG = config.getbool('app.debug', APPMODE == 'dev')
TEMPLATE_DEBUG = DEBUG

# Security
ALLOWED_HOSTS = config.getlist('site.allowed_hosts')
# CSRF Cookies can only be sent when Referer == us
CSRF_COOKIE_SAMESITE = 'Strict'

# Sessions
SESSION_COOKIE_SECURE = APPMODE == 'prod'


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'appel_crises',
]

if APPMODE != 'prod':
    INSTALLED_APPS += [
        # Run with whitenoise in development too. Avoids issues with
        # invalid {% static '/appel_crises/...' %} that fail in production.
        'whitenoise.runserver_nostatic',
    ]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'appel_crises.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'appel_crises.wsgi.application'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {'console': {'class': 'logging.StreamHandler'}},
    'root': {'handlers': ['console'], 'level': 'INFO'},
}

psql_db = {
    'ENGINE': 'django.db.backends.postgresql',
    'HOST': config.getstr('db.host', 'localhost'),
    'NAME': config.getstr('db.name'),
    'PASSWORD': config.getstr("db.password"),
    'PORT': config.getstr('db.port', ''),
    'USER': config.getstr("db.user"),
}
sqlite_db = {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}

_db_engine = config.getstr('db.database', 'sqlite')

DATABASES = {'default': sqlite_db if _db_engine == 'sqlite' else psql_db}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation'
        '.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {'min_length': 10},
    },
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = config.getstr('i18n.language', 'fr')

TIME_ZONE = config.getstr('i18n.tz', 'Europe/Paris')

USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = config.getstr('site.assets_url', '/assets/')
STATIC_ROOT = os.path.join(BASE_DIR, 'appel_crises', 'assets')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# SendinBlue Settings
SENDIN_BLUE_API_KEY = config.getstr('mail.sendinblue_api_key')
MAIN_EMAIL = config.getstr('mail.main_email')
SIGNATURE_TEMPLATE_ID = config.getint('mail.confirmation_email_id', 47)

# A 'catchall' address for emails.
# If set to `test+{}@gmail.com`, emails sent to `jules.cesar@example.org`
# will be rewritten to `test+jules.cesar_at_example.org@gmail.com`
MAILING_CATCHALL = config.getstr('mail.catchall', '')

# Sentry settings
SENTRY_ENV = config.getstr('sentry.environment', APPMODE)
sentry_sdk.init(
    dsn=config.getstr('sentry.api_key'),
    integrations=[DjangoIntegration()],
    environment=APPMODE,
    debug=DEBUG,
)

# MtCapcha settings
MTCAPTCHA_PRIVATE_KEY = config.getstr('mtcaptcha.private_key', '')

# Max workers for sending mail
# Mostly useful for sqlite use, where 1 max worker can work
_default_max_thread_workers = 1 if _db_engine == 'sqlite' else None
MAX_THREAD_WORKERS = config.getint(
    'app.max_thread_workers', _default_max_thread_workers
)
