#!/usr/bin/env python3
# -*-encoding:UTF-8-*-
"""
Django settings for ICQBPMSSOJ project.

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

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

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


import os

import raven
from copy import deepcopy
from myutils.shortcuts import get_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__)))


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


production_env = get_env("OJ_ENV", "dev") == "production"
if production_env:
    from .production_settings import *
else:
    from .dev_settings import *

with open(os.path.join(DATA_DIR, "config", "secret.key"), "r") as f:
    SECRET_KEY = f.read()

# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = '#)er^8sqpy6y+3peqg&1lyy+3!m-0@f9bwidv+mgc^4vdib#xg'
# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = True
# ALLOWED_HOSTS = []

VENDOR_APPS = [
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'rest_framework',
    'raven.contrib.django.raven_compat'
]


LOCAL_APPS = [
    'account',
    'announcement',
    'conf',
    'problem',
    'contest',
    'myutils',
    'submission',
    'options',
    'judge',
]

INSTALLED_APPS = VENDOR_APPS + LOCAL_APPS

# it has loading order!
MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'account.middleware.APITokenAuthMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'account.middleware.AdminRoleRequiredMiddleware',
    'account.middleware.SessionRecordMiddleware',
    'account.middleware.LogSqlMiddleware',
]

ROOT_URLCONF = 'ICQBPMSSOJ.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 'DIRS': [os.path.join(BASE_DIR, 'templates')],  Default
        '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 = 'ICQBPMSSOJ.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/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/1.11/howto/static-files/
# STATIC_URL = '/static/'
# Default:/static/

STATIC_URL = '/public/'


# config yourself

REST_FRAMEWORK = {
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    )
}

AUTH_USER_MODEL = 'account.User'


# test case file and log file
TEST_CASE_DIR = os.path.join(DATA_DIR, "test_case")  # /data/test_case  ->for production
LOG_PATH = os.path.join(DATA_DIR, "log")

# test file and log file
AVATAR_URI_PREFIX = "/public/avatar"
AVATAR_UPLOAD_DIR = f"{DATA_DIR}{AVATAR_URI_PREFIX}"

# upload fileprefix and path
UPLOAD_PREFIX = "/public/upload"
UPLOAD_DIR = f"{DATA_DIR}{UPLOAD_PREFIX}"

# static file:/data/public
STATICFILES_DIRS = [os.path.join(DATA_DIR, "public")]


LOGGING_HANDLERS = ['console', 'sentry'] if production_env else ['console']
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '[%(asctime)s] - [%(levelname)s] - [%(name)s:%(linneno)d] - %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S'
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        },
        'sentry': {
            'level': 'ERROR',
            'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
            'formatter': 'standard'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': LOGGING_HANDLERS,
            'level': 'ERROR',
            'propagate': True,
        },
        'django.db.backends': {
            'handlers': LOGGING_HANDLERS,
            'level': 'ERROR',
            'propagate': True,
        },
        '': {
            'handlers': LOGGING_HANDLERS,
            'level': 'WARNING',
            'propagate': True,
        }
    },
}

# redis://[:password]@localhost:6379/0  choose
# rediss://[:password]@localhost:6379/0
# unix://[:password]@/path/to/socket.sock?db=0
REDIS_URL = "redis://%s:%s" % (REDIS_CONF["host"], REDIS_CONF["port"])


# reference
# https://docs.djangoproject.com/en/dev/ref/settings/
# https://docs.djangoproject.com/en/dev/topics/cache/#cache-key-transformation
def redis_config(db):
    #
    def make_key(key, key_prefix, version):
        return key

    # "TIMEOUT": None,
    return {
        "BACKEND": "myutils.cache.MyRedisCache",
        "LOCATION": f"{REDIS_URL}/{db}",
        "TIMEOUT": None,
        "KEY_PREFIX": "",
        "KEY_FUNCTION": make_key
    }


#
CACHES = {
    "default": redis_config(db=1)
}

# this will be called in view to set the session of the website
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

CELERY_RESULT_BACKEND = f"{REDIS_URL}/2"
BROKER_URL = f"{REDIS_URL}/3"
#
CELERY_TASK_SOFT_TIME_LIMIT = CELERY_TASK_TIME_LIMIT = 180
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_TASK_SERIALIZER = "json"

# sentry's client raven
RAVEN_CONFIG = {
    'dsn': 'https://9eeee24e3acb48899e06395c778c111d@sentry.io/1437557'
}

# IP header，need to be reset
IP_HEADER = "HTTP_X_REAL_IP"









