# coding=utf-8
import logging
import logging.config
import os
import redis
from kedong.utils import parse_config_new


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BASE_DIR)
SECRET_KEY = 'qqou#yc6-2kj==&-$lr%q(1&5uqayp+zx$423q_%)fmsvms(e1'
DEBUG = True
ALLOWED_HOSTS = ["*"]
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'smartfarming',
    'corsheaders',
]
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 'smartfarming.middleware.response.ResponseMiddleware'
]


REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'smartfarming.permissions.smking.LoginPermission',
    )
}

CORS_ORIGIN_WHITELIST = ()
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)
CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

ROOT_URLCONF = 'kedong.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 = 'kedong.wsgi.application'
CONFIG = parse_config_new(BASE_DIR)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': CONFIG['bigdata']['mysql_db'],
        'USER': CONFIG['bigdata']['mysql_user'],
        'PASSWORD': CONFIG['bigdata']['mysql_password'],
        'HOST': CONFIG['bigdata']['mysql_host'],
        'PORT': CONFIG['bigdata']['mysql_port'],
        'OPTIONS': {'charset': 'utf8mb4'}
    },
    "mqtt_record_db": {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': CONFIG['mqtt_record_db']['mysql_db'],
        'USER': CONFIG['mqtt_record_db']['mysql_user'],
        'PASSWORD': CONFIG['mqtt_record_db']['mysql_password'],
        'HOST': CONFIG['mqtt_record_db']['mysql_host'],
        'PORT': CONFIG['mqtt_record_db']['mysql_port'],
        'OPTIONS': {'charset': 'utf8mb4'}
    }
}
# redis连接
# REDIS 订阅数据
redis_host = CONFIG["redis"]['ip']
redis_port = CONFIG["redis"]['port']
redis_password = CONFIG["redis"]['password']
redis_db = CONFIG["redis_db"]
# 下发指令 
pub_redis = redis.ConnectionPool(
    host=redis_host,
    port=redis_port,
    password=redis_password,
    db=11,
    decode_responses=True
)
pub_redis_pool = redis.StrictRedis(connection_pool=pub_redis)
# REDIS 验证码
captcha_redis = redis.ConnectionPool(
    host=redis_host,
    port=redis_port,
    password=redis_password,
    db=1,
    decode_responses=True
)   
captcha_redis_pool = redis.StrictRedis(connection_pool=captcha_redis)
# FTP监听
ftp_redis = redis.ConnectionPool(
    host=redis_host,
    port=redis_port,
    password=redis_password,
    db=12,
    decode_responses=True
)
ftp_redis_pool = redis.StrictRedis(connection_pool=ftp_redis)

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


LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False


STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_ROOT = CONFIG.get("media") 
os.makedirs(MEDIA_ROOT) if not os.path.exists(MEDIA_ROOT) else None 
MEDIA_URL = '/media/'

# 日志处理系统
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {  # 将日志输出到控制台
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'django': {  # 将日志写入到文件
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': 'logs/django.log',
            'when': 'midnight',
            'backupCount': 30,
            'encoding': 'utf-8',
            'formatter': 'verbose'
        },
        'myapp': {  # 将日志写入到文件
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': 'logs/app.log',
            'when': 'midnight',
            'backupCount': 30,
            'encoding': 'utf-8',
            'formatter': 'verbose'
        },
        'data_ingestion': {  # 将日志写入到文件
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': 'logs/data_ingestion.log',
            'when': 'midnight',
            'backupCount': 30,
            'encoding': 'utf-8',
            'formatter': 'verbose'
        },
        'other':{  # 记录utils中日志
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': 'logs/other.log',
            'when': 'midnight',
            'backupCount': 30,
            'encoding': 'utf-8',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {  # 默认的日志器
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': True,
        },
        'myapp': {  # 自定义的日志器
            'handlers': ['myapp'],
            'level': 'WARNING',
            'propagate': True,
        },
        'data_ingestion': {  # 自定义的日志器
            'handlers': ['data_ingestion'],
            'level': 'WARNING',
            'propagate': True,
        },
        'other': {  # 自定义的日志器
            'handlers': ['other'],
            'level': 'WARNING',
            'propagate': True,
        },
    },
    'formatters': {
        'simple': {
            'format': '{asctime} - {levelname} - {message}',
            'style': '{',
        },
        'verbose': {
            'format': '{asctime} - {levelname} - {name} - {message}',
            'style': '{',
        },
    },
}

logging.config.dictConfig(LOGGING)
