"""
Django settings for SCORE Bot project.

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

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

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

import os
import socket
from common import constants

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

DEBUG = constants.DEBUG

ALLOWED_HOSTS = ["0.0.0.0"]  # Update as appropriate

SAML_FOLDER = os.path.join(BASE_DIR, 'saml')

SESSION_ENGINE = 'django.contrib.sessions.backends.file'

SECURE_FLAG = constants.SECURE_FLAG

if SECURE_FLAG:
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    SESSION_EXPIRE_AT_BROWSER_CLOSE = True

CSRF_TRUSTED_ORIGINS = []

SECRET_KEY = constants.DJANGO_KEY

# Application definition

INSTALLED_APPS = [
    'core',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_markup',
    'rest_framework',
]

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

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


DATABASES = {

    "default": {"ENGINE": "django.db.backends.mysql",
                'NAME': constants.DB_NAME,
                "USER": constants.SB_SQL_USER,  # User with R/W access to the mysql DB
                "PASSWORD": constants.SB_SQL_PASSWORD,  # Password for the above username
                "HOST": constants.DB_HOST,  # Hostname (or IP) where the DB is located
                "PORT": constants.DB_PORT,  # TCP port number (3306 is the default)
                "OPTIONS": {"init_command": "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED"}
                }
}


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'packages/notifications/templates'),
            os.path.join(BASE_DIR, 'scorebot/templates'),
        ],
        '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',
            ],
            'debug': DEBUG,
        },
    },
]


# Password validation
# https://docs.djangoproject.com/en/2.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/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATICFILES_FINDERS = (
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
)


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        "verbose": {
            "format": "%(asctime)s %(levelname)s %(module)s::%(funcName)s::%(lineno)d %(message)s",
        },
        "simple": {
            "format": "%(levelname)s %(message)s",
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
            'formatter': 'verbose',
        },
        'console': {
            # This is the uWSGI/runserver console/log output.  We don't need INFO/DEBUG output here,
            # since it's already in other places.
            'level': 'WARNING',
            'class': 'logging.StreamHandler',
            "formatter": "verbose",
        },
        'mail_admins': {
            'level': 'CRITICAL',
            'filters': ['require_debug_false'],
            'include_html': True,
            'class': 'django.utils.log.AdminEmailHandler',
        },
        'logfile': {
            # When running under uWSGI cannot use the rotating file handler, otherwise 10 process
            # all try to rotate the single log file.
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': constants.scorebot_log,
            'formatter': 'verbose',
            'mode': 'a',
            'encoding': 'utf8',
        },
        'error_email': {
            'level': 'CRITICAL',
            'class': 'logging.handlers.SMTPHandler',
            'formatter': 'verbose',
            'mailhost': constants.DEFAULT_SMTP_SERVER,
            'fromaddr': constants.SCOREBOT_DL_EMAIL_ADDRESS_CRITICAL,
            'toaddrs': [constants.SCOREBOT_DL_EMAIL_ADDRESS_CRITICAL, ],
            'subject': 'SCORE Bot CRITICAL Error on {0}'.format(socket.gethostname())
        },
    },
    'loggers': {
        '': {
            'handlers': ['null', 'console', 'logfile', 'error_email'],
            'level': 'DEBUG' if DEBUG else 'INFO',
            'propagate': True,
        },
        'django': {
            'handlers': ['console', 'logfile'] if DEBUG else ['null'],
            'level': 'INFO' if DEBUG else 'INFO',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['console', 'logfile', 'mail_admins'],
            'level': 'WARNING' if DEBUG else 'WARNING',
            'propagate': False,
        },
        'django.db.backends': {
            'handlers': ['console', 'logfile', 'mail_admins'],
            'level': 'ERROR' if DEBUG else 'ERROR',
            'propagate': False,
        },
    }
}
