"""
Django settings for Lutece project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import environ
import os
from datetime import timedelta

from Lutece.config import RunTimeEnv, get_runtime_configuration

env = environ.Env()

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

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'django_gravatar',
    'gunicorn',
    'graphene_django',
    'corsheaders',
    'channels',
]

LUTECE_APPS = [
    'user',
    'problem',
    'judge',
    'submission',
    'data',
    'article',
    'record',
    'reply',
    'contest',
]

INSTALLED_APPS += LUTECE_APPS

GRAPHENE = {
    'SCHEMA': 'Lutece.schema.schema',
    'MIDDLEWARE': [
        'graphql_jwt.middleware.JSONWebTokenMiddleware',
    ],
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'graphql_jwt.middleware.JSONWebTokenMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

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

# Django channels
ASGI_APPLICATION = "Lutece.routing.application"

ROOT_URLCONF = 'Lutece.urls'

GRAPHQL_JWT = {
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_EXPIRATION_DELTA': timedelta(hours=12),
    'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7),
    'JWT_PAYLOAD_HANDLER': 'user.jwt.payload.payload_handler',
    'JWT_DECODE_HANDLER': 'user.jwt.decode.decode_handler',
}

WSGI_APPLICATION = 'Lutece.wsgi.application'
AUTH_USER_MODEL = 'user.User'

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
]

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

# LOGIN Session: 12 hour
SESSION_COOKIE_AGE = 12 * 60 * 60

# Templates config
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',
            ],
        },
    },
]

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

STATIC_URL = '/static/'

STATICFILES_FINDERS = (
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder"
)

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

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

# Lutece setting
mode = RunTimeEnv.value_of(env.get_value('lutece_runtime_mode', str, 'dev'))
print(f'- start server with {mode}')
config = get_runtime_configuration(mode).get_runtime_variables(check=True)

# Inject config variables to settings

# The frontend dist dir
STATICFILES_DIRS = config.get('STATICFILES_DIRS')

# The DB settings
DATABASES = config.get('DATABASES')

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

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

# The allowed hosts
ALLOWED_HOSTS = config.get('ALLOWED_HOSTS')

# CORS settings
CORS_ORIGIN_ALLOW_ALL = config.get('CORS_ORIGIN_ALLOW_ALL')

# The channel layers
CHANNEL_LAYERS = config.get('CHANNEL_LAYERS')

# The data server configuration
DATA_SERVER = config.get('DATA_SERVER')

# The judge configuration
JUDGE = config.get('JUDGE')

# Max 200 mb file
FILE_UPLOAD_MAX_MEMORY_SIZE = 200 * 1024 * 1024
DATA_UPLOAD_MAX_MEMORY_SIZE = FILE_UPLOAD_MAX_MEMORY_SIZE
