"""
Django settings for wdoneops project.

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

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 os
import sys
import configparser

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
# sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

cfg = configparser.ConfigParser()
cfg.read(os.path.join(BASE_DIR, 'wdoneops.conf'))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ru$o+lso(6y=p!=a3%!!2ye03zrker1lg74_#pjimvy56(=bn3'

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

ALLOWED_HOSTS = ['*']

# 解决nginx部署跳转404
USE_X_FORWARDED_HOST = True

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
    'accounts',
    'workflow',
    'common',
    'cmdb',
    'dns_pod',
    'ssh',
    'job',
    'tools',
    'django_celery_results',
    'django_celery_beat',
]

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 = 'wdoneops.urls'

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',
                'wdoneops.context_processors.global_info',
            ]
        },
    },
]

WSGI_APPLICATION = 'wdoneops.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': cfg.get('db_default', 'database'),
        'USER': cfg.get('db_default', 'user'),
        'PASSWORD': cfg.get('db_default', 'password'),
        'HOST': cfg.get('db_default', 'host'),
        'PORT': cfg.get('db_default', 'port'),
        'TEST': {
            'NAME': cfg.get('db_default', 'test_database'),
            'CHARSET': 'utf8',
        },
    },
    'bind_prod': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': cfg.get('db_bind_prod', 'database'),
        'USER': cfg.get('db_bind_prod', 'user'),
        'PASSWORD': cfg.get('db_bind_prod', 'password'),
        'HOST': cfg.get('db_bind_prod', 'host'),
        'PORT': cfg.get('db_bind_prod', 'port'),
        'OPTIONS': {'isolation_level': None}
    },
    'bind_beta': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': cfg.get('db_bind_beta', 'database'),
        'USER': cfg.get('db_bind_beta', 'user'),
        'PASSWORD': cfg.get('db_bind_beta', 'password'),
        'HOST': cfg.get('db_bind_beta', 'host'),
        'PORT': cfg.get('db_bind_beta', 'port'),
        'OPTIONS': {'isolation_level': None}
    },
    'bind_pre': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': cfg.get('db_bind_pre', 'database'),
        'USER': cfg.get('db_bind_pre', 'user'),
        'PASSWORD': cfg.get('db_bind_pre', 'password'),
        'HOST': cfg.get('db_bind_pre', 'host'),
        'PORT': cfg.get('db_bind_pre', 'port'),
        'OPTIONS': {'isolation_level': None}
    },
    'bind_test': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': cfg.get('db_bind_test', 'database'),
        'USER': cfg.get('db_bind_test', 'user'),
        'PASSWORD': cfg.get('db_bind_test', 'password'),
        'HOST': cfg.get('db_bind_test', 'host'),
        'PORT': cfg.get('db_bind_test', 'port'),
        'OPTIONS': {'isolation_level': None}
    },
    'bind_dev': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': cfg.get('db_bind_dev', 'database'),
        'USER': cfg.get('db_bind_dev', 'user'),
        'PASSWORD': cfg.get('db_bind_dev', 'password'),
        'HOST': cfg.get('db_bind_dev', 'host'),
        'PORT': cfg.get('db_bind_dev', 'port'),
        'OPTIONS': {'isolation_level': None}
    }
}

# DATABASE_ROUTERS = [
#     'wdoneops.database_router.DatabaseAppsRouter'
# ]
# DATABASE_APPS_MAPPING = {
#         # example:
#         # 'app_label': 'database_name',
#         # app_label 需加到INSTALLED_APPS中，它们是通过startapp创建的app
# }

# 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 = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

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

STATIC_URL = '/static/'
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')  # 图片存取的绝对路径
MEDIA_URL = '/media/'   # 图片存取的相对路径

# 扩展django admin里users字段，指定了user/models.py里的class User
AUTH_USER_MODEL = "accounts.User"

# django-rest-framework api
REST_FRAMEWORK = {
    'DEFAULT_VERSION': 'v1',            # 默认版本
    'ALLOWED_VERSIONS': ['v1', 'v2'],   # 允许的版本
    'VERSION_PARAM': 'version'          # URL中获取值的key
}

# LDAP
ENABLE_LDAP = False
if ENABLE_LDAP:
    AUTHENTICATION_BACKENDS = (
        'django_auth_ldap.backend.LDAPBackend',       # 配置为先使用LDAP认证，如通过认证则不再使用后面的认证方式
        'django.contrib.auth.backends.ModelBackend',  # django系统中手动创建的用户也可使用，优先级靠后。注意这2行的顺序
    )

    AUTH_LDAP_SERVER_URI = "ldap://127.0.0.1:389"
    AUTH_LDAP_USER_DN_TEMPLATE = "cn=%(user)s,ou=Staff,dc=example,dc=com"
    AUTH_LDAP_ALWAYS_UPDATE_USER = True      # 每次登录从ldap同步用户信息
    AUTH_LDAP_USER_ATTR_MAP = {              # key为user字段名，value为ldap中字段名，用户同步信息
        "username": "cn",
        "display": "name",
        "email": "mail"
    }

ASGI_APPLICATION = 'wdoneops.routing.application'

# channel配置
CHANNEL_LAYERS = {
    "default": {
        # This example app uses the Redis channel layer implementation channels_redis
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

# Celery
# CELERY_ENABLE_UTC = False
# DJANGO_CELERY_BEAT_TZ_AWARE = False
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/15'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
CELERY_IMPORTS = ('job.tasks.task', 'workflow.tasks.network')
CELERYD_MAX_TASKS_PER_CHILD = 200

DATA_UPLOAD_MAX_NUMBER_FIELDS = 10240  # higher than the count of fields

# Log配置
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d][%(levelname)s]- %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '{}/logs/{}'.format(BASE_DIR, cfg.get('log', 'log_file')),
            'maxBytes': 1024 * 1024 * 100,  # 5 MB
            'backupCount': 5,
            'formatter': 'verbose',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
        'sql': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '{}/logs/{}'.format(BASE_DIR, cfg.get('log', 'sql_log_file')),
            'maxBytes': 1024 * 1024 * 100,    # 5 MB
            'backupCount': 5,
            'formatter': 'verbose',
        }
    },
    'loggers': {
        'default': {             # default日志，存放于log中
            'handlers': ['default'],
            'level': 'DEBUG',
        },
        'django_auth_ldap': {    # django_auth_ldap模块相关日志
            'handlers': ['default'],
            'level': 'DEBUG',
        },
        'django.db': {           # 打印SQL语句到console，方便开发
            'handlers': ['sql'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'django.request': {      # 打印请求错误堆栈信息到console，方便开发
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}
