"""
Django settings for djapp project.

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

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

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

import os
import sys
import getconf
import dj_database_url


TESTING = False


# Clever Cloud hosting
if 'POSTGRESQL_ADDON_URI' in os.environ:
    os.environ['DJAPP_DB_URL'] = os.environ.get('POSTGRESQL_ADDON_URI')


# 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('djapp', ['./local_settings.ini'])

ENV = config.getstr('djapp.env')
FRONT_URL = config.getstr('djapp.front_url')

MAINTENANCE = config.getbool('djapp.maintenance', False)

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config.getstr('django.secret')


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config.getbool('django.debug')

ALLOWED_HOSTS = config.getlist('django.allowed_hosts', ['*'])

IN_CELERY_WORKER_PROCESS = sys.argv and sys.argv[0].endswith('celery') and 'worker' in sys.argv

USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

INTERNAL_IPS = [
    '127.0.0.1',
]


SITE_URL = config.getstr('djapp.site_url', '')


# Application definition

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

    'django_extensions',
    'debug_toolbar',
    'django_filters',
    'anymail',
    'rest_framework',
    'rest_framework_gis',
    'corsheaders',

    'djapp',
]

# Accept origins from config or all if default
CORS_ORIGIN_REGEX_WHITELIST = config.getlist('django.cors_allowed_domains', [])

# Allow the browser to send the following headers
CORS_ALLOW_HEADERS = ('content-type', 'accept', 'origin', 'authorization')


if DEBUG:
    CORS_ORIGIN_ALLOW_ALL = True


AUTH_USER_MODEL = 'djapp.User'


MIDDLEWARE = [
    'djapp.utils.logfilters.RequestMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'djapp.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 = 'djapp.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': dj_database_url.parse(config.getstr('db.url').replace('postgresql:', 'postgis:')),
}


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

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


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

LANGUAGE_CODE = 'fr-fr'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = 'dist/static'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


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



LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,

    'filters': {
        'request_id': {
            '()': 'request_id.logging.RequestIdFilter',
        },
        'session_id': {
            '()': 'djapp.utils.logfilters.SessionIdFilter',
        },
    },

    'formatters': {
        'simple': {
            'format': '[%(asctime)s] %(levelname)s sid=%(session_id)s rid=%(request_id)s %(name)s %(message)s',  # NOQA
            'datefmt': '%Y-%m-%dT%H:%M:%S%z',
        },
        'short': {
            'format': '[%(asctime)s] %(levelname)s %(module)s %(message)s',  # NOQA
            'datefmt': '%Y-%m-%dT%H:%M:%S%z',
        },
    },

    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': config.getstr('log.formatter', 'simple'),
            'filters': ['request_id', 'session_id'],
        },

    },

    'loggers': {
        'django.request': {
            'level': 'WARNING',
        },
        'asyncio': {
            'level': config.getstr('log.asyncio', 'WARNING'),
        },
        'parso': {  # ipython parser
            'level': config.getstr('log.parso', 'WARNING'),
        },
        'chardet': {  # ipdb
            'level': config.getstr('log.chardet', 'WARNING'),
        },
        'factory': {
            'level': config.getstr('log.factory', 'WARNING'),
        },
        'faker': {
            'level': config.getstr('log.faker', 'WARNING'),
        },
        'flake8': {
            'level': config.getstr('log.flake8', 'WARNING'),
        },
        'urllib3': {
            'level': config.getstr('log.requests', 'WARNING'),
        },
        'django.db': {
            'level': config.getstr('log.db_level', 'WARNING'),
        },
        'celery': {
            'level': config.getstr('log.level', 'INFO'),
        },
        'djapp': {
            'level': config.getstr('log.level', 'INFO'),
        },
        '': {
            'handlers': [],
            'level': 'DEBUG',
        },
    }
}


if IN_CELERY_WORKER_PROCESS:
    LOGGING['loggers']['']['handlers'].append('celery')
else:
    LOGGING['loggers']['']['handlers'].append('console')


REQUEST_ID_HEADER = 'HTTP_X_AMZ_CF_ID'


SHELL_PLUS_PRE_IMPORTS = [
    ('collections', ('Counter',)),
    ('django.db', ('connection',)),
    ('django.db.transaction', ('atomic',)),
    ('django.db.models', ('Func',)),
    ('django.db.models.expressions', ('RawSQL',)),
    'time',
    'datetime',
    ('pprint', ('pprint',)),
    ('djapp', ('models',)),
]


DEFAULT_FROM_EMAIL = config.getstr('emails.sender')
EMAIL_BACKEND = config.getstr('emails.backend')
EMAIL_WHITELIST = config.getlist('emails.whitelist', None)

EMAIL_HOST = config.getstr('emails.smtp_host')
EMAIL_PORT = config.getstr('emails.smtp_port')
EMAIL_HOST_USER = config.getstr('emails.smtp_user')
EMAIL_HOST_PASSWORD = config.getstr('emails.smtp_password')

ANYMAIL = {
    "SENDINBLUE_API_KEY": config.getstr('emails.sendingblue_api_key')
}

RECAPTCHA_SECRET_KEY = config.getstr('recaptcha.secret_key')

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
    ],
    'UNICODE_JSON': True,
}
