"""
Django settings for coffee project.

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

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 ldap
from django_auth_ldap.config import LDAPSearch, PosixGroupType


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')

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

ALLOWED_HOSTS = ['*']


# Paths

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

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

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')


# Environment variables (imported from your .env file)
EMAIL_HOST = os.getenv('EMAIL_HOST')


# Filter settings
FILTERS_EMPTY_CHOICE_LABEL = ''


# Settings for auto-resizing user-uploaded profile pictures
DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG'
DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': '.jpg'}
DJANGORESIZED_DEFAULT_QUALITY = 100
DJANGORESIZED_DEFAULT_SIZE = [300, 300]


# Auto-created fields
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'


# Logging
# LOGGING = {'version': 1,
#            'disable_existing_loggers': False,
#            'formatters': {'verbose': {'format': '{asctime} {message}',
#                                       'datefmt': '%d.%m.%Y %H:%M:%S:',
#                                       'style': '{'}},
#            'handlers': {'syncldap': {'level': 'INFO',
#                                      'class': 'logging.FileHandler',
#                                      'filename': os.path.join(BASE_DIR,
#                                                               'chiffee',
#                                                               'logs',
#                                                               'syncldap.txt'),
#                                      'formatter': 'verbose'}},
#            'loggers': {'syncldap': {'handlers': ['syncldap'],
#                                     'level': 'INFO',
#                                     'propagate': True}}}


# LDAP

AUTH_LDAP_SERVER_URI = os.getenv('AUTH_LDAP_SERVER_URI')
AUTH_LDAP_BIND_DN = os.getenv('AUTH_LDAP_BIND_DN')
AUTH_LDAP_BIND_PASSWORD = os.getenv('AUTH_LDAP_BIND_PASSWORD')
AUTH_LDAP_START_TLS = os.getenv('AUTH_LDAP_START_TLS')

AUTH_LDAP_BASE_DN = os.getenv('AUTH_LDAP_BASE_DN')
AUTH_LDAP_OU_GROUPS = os.getenv('AUTH_LDAP_OU_GROUPS')
AUTH_LDAP_CN_ADMINS = os.getenv('AUTH_LDAP_CN_ADMINS')

AUTH_LDAP_USER_SEARCH = LDAPSearch(AUTH_LDAP_BASE_DN,
                                   ldap.SCOPE_SUBTREE,
                                   '(uid=%(user)s)')

AUTH_LDAP_USER_ATTR_MAP = {
    'username': os.getenv('AUTH_LDAP_USER_ATTR_MAP_USERNAME'),
    'first_name': os.getenv('AUTH_LDAP_USER_ATTR_MAP_FIRST_NAME'),
    'last_name': os.getenv('AUTH_LDAP_USER_ATTR_MAP_LAST_NAME'),
    'email': os.getenv('AUTH_LDAP_USER_ATTR_MAP_EMAIL')}

AUTH_LDAP_GROUP_TYPE = PosixGroupType()

AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
    AUTH_LDAP_OU_GROUPS + ',' + AUTH_LDAP_BASE_DN,
    ldap.SCOPE_SUBTREE,
    '(objectClass=posixGroup)')

AUTH_LDAP_USER_FLAGS_BY_GROUP = {'is_staff': (f'{AUTH_LDAP_CN_ADMINS},'
                                              f'{AUTH_LDAP_OU_GROUPS},'
                                              f'{AUTH_LDAP_BASE_DN}'),
                                 'is_superuser': (f'{AUTH_LDAP_CN_ADMINS},'
                                                  f'{AUTH_LDAP_OU_GROUPS},'
                                                  f'{AUTH_LDAP_BASE_DN}')}

AUTH_LDAP_MIRROR_GROUPS = os.getenv('AUTH_LDAP_MIRROR_GROUPS').split(' ')

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


# Application definition

INSTALLED_APPS = ['django.contrib.admin',
                  'django.contrib.auth',
                  'django.contrib.contenttypes',
                  'django.contrib.sessions',
                  'django.contrib.messages',
                  'django.contrib.staticfiles',
                  'chiffee',
                  'django_extensions',
                  'django_filters',
                  'django_resized']

MIDDLEWARE = ['django.middleware.security.SecurityMiddleware',
              '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 = 'coffee.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 = 'coffee.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3',
                         'NAME': os.path.join(BASE_DIR, 'db.sqlite3')}}


# 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')},
                            {'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 = 'de-DE'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
