"""
Django settings for kankan project.

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

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

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

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

FORCE_SCRIPT_NAME = os.environ.get('FORCE_SCRIPT_NAME', '/female_ghost_charm/')


DEBUG = True

SECRET_KEY = os.environ.get('SECRET_KEY', 'secret_key')

ALLOWED_HOSTS = ['*']


CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost',
    'http://localhost:8001',
    'http://localhost:8002',
    'http://localhost:8000',
    'http://localhost:8081',
    'http://localhost:8888',
    'http://localhost:8889',
    'http://localhost:8080',
    'http://localhost:8999',
)

if 'WHITELIST' in os.environ:
    whitelist = os.environ['WHITELIST']
    for host in whitelist.split(','):
        CORS_ORIGIN_WHITELIST += (host,)


CDN_HOSTNAME = os.environ.get('CDN_HOSTNAME', '')

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

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',
    'corsheaders.middleware.CorsMiddleware',
]

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

if os.environ.get('DOCKERIZED'):
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'HOST': os.environ.get('POSTGRES_SERVICE', 'postgres'),
            'NAME': os.environ.get('POSTGRES_DB', 'postgres'),
            'PASSWORD': os.environ.get('POSTGRES_PASSWORD', 'postgres'),
            'PORT': os.environ.get('POSTGRES_PORT', 5432),
            'USER': os.environ.get('POSTGRES_USER', 'postgres')
        }
    }

REDIS_HOST = os.environ.get('REDIS_HOST', 'redis')
REDIS_CACHE_LOCATION = '{}://{}:6379'.format(REDIS_HOST, REDIS_HOST)

CACHES = {
    'default': {
        "BACKEND": 'django_redis.cache.RedisCache',
        'LOCATION': REDIS_CACHE_LOCATION,
        'TIMEOUT': 259200,
        'OPTIONS': {
            'COMPRESSOR': 'django_redis.compressors.zlib.ZlibCompressor',
            'IGNORE_EXCEPTIONS': True,
        }
    },
}

OAUTH2_PROVIDER = {
    'SCOPES': {'read': 'Read scope', 'write': 'Write scope'},
    'ACCESS_TOKEN_EXPIRE_SECONDS': 3600,  # 1 hour
    'REFRESH_TOKEN_EXPIRE_SECONDS': 86400,  # 24 hour
    'OAUTH_DELETE_EXPIRED': True,
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
   'DEFAULT_PAGINATION_CLASS':
        'rest_framework.pagination.LimitOffsetPagination',
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
    'NON_FIELD_ERRORS_KEY': 'error_code'  # RESPONSE/ERROR RENDERING
}

START_APPS = []

INSTALLED_APPS += START_APPS

THIRD_PARTY_APPS = [
    'oauth2_provider',
    'django_extensions',
    'corsheaders',
    'rest_framework',
    'drf_yasg',
]

INSTALLED_APPS += THIRD_PARTY_APPS

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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',
            ],
        },
    },
]

LOGGING = {
           'version': 1,
           'disable_existing_loggers': False,
           'formatters': {
               'verbose': {
                   'format': '[%(asctime)s][%(name)s:%(lineno)s][%(levelname)s] %(message)s',
    'datefmt': '%Y/%b/%d %H:%M:%S'
               },
               'colored': {'()': 'colorlog.ColoredFormatter',
                           'format': '[%(log_color)s%(asctime)s%(reset)s][%(name)s:%(lineno)s][%(log_color)s%(levelname)s%(reset)s] %(message)s',
                           'datefmt': '%Y/%b/%d %H:%M:%S',
                           'log_colors': {'DEBUG': 'cyan',
                                          'INFO': 'green',
                                          'WARNING': 'bold_yellow',
                                          'ERROR': 'red',
                                          'CRITICAL': 'red,bg_white'},
                           'secondary_log_colors': {},
                           'style': '%'},
           },
           'handlers': {
               'console': {
                   'level': 'DEBUG',
                   'class': 'logging.StreamHandler',
                   'formatter': 'colored'
               },
               'mail_admins': {
                   'level': 'ERROR',
                   'class': 'django.utils.log.AdminEmailHandler',
               },
           },
           'loggers': {
               'django': {
                   'handlers': ['console'],
                   'propagate': True,
               },
               'django.request': {
                   'handlers': ['mail_admins'],
                   'level': 'ERROR',
               },
           }
}

__app_logging = {'handlers': ['console', ],
                 'level': 'DEBUG',
                 'propagate': True}

for proj_app in START_APPS:
    LOGGING.get('loggers').update({proj_app: __app_logging})

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

LANGUAGE_CODE = os.environ.get('LANGUAGE_CODE', 'en-us')
TIME_ZONE = os.environ.get('TIME_ZONE', 'Asia/Shanghai')
USE_TZ = True

STATIC_URL = '/static/'
STATIC_ROOT = 'static'
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')
MEDIA_URL = '/upload/'

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

CELERY_RESULT_BACKEND = 'rpc://'
CELERY_TIMEZONE = TIME_ZONE

if os.environ.get('ENV') == 'production':
    from .production_settings import *
else:
    from .development_settings import *

if os.environ.get('GKE'):
    from .gke_settings import *
