"""
Django settings for simqsvr project.

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

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

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

import os
import logging
from pathlib import Path
from simqsvr.version import VERSION

_logger = logging.getLogger(__name__)

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "Y536wJqNpbSx3szOj5UyNQKiKdHNaIBbZBxfBeHAenzsD61cUvT5ZIP9JUX7A1BBTMrEky9bbeWGSSZYfJWGoybB101bVaVrhu5zGnYvS4tfat2pMwLy3a8O"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
    "localhost",
    "127.0.0.1",
]


# Application definition

INSTALLED_APPS = [
    "django_apis",
    "simqsvr",
    "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",
]

ROOT_URLCONF = "simqsvr.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 = "simqsvr.wsgi.application"


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DEFAULT_DATABASE = os.path.abspath("database/db.sqlite3")
try:
    os.makedirs(os.path.dirname(DEFAULT_DATABASE), exist_ok=True)
except Exception as error:
    _logger.warning(
        "Create DEFAULT_DATABASE root failed: root=%s",
        os.path.dirname(DEFAULT_DATABASE),
    )

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": DEFAULT_DATABASE,
    }
}


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

LANGUAGE_CODE = "zh-hans"

TIME_ZONE = "Asia/Shanghai"

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = "simq/admin/static/"
STATIC_ROOT = "/www/static/simq/admin/static/"
MEDIA_URL = "simq/admin/upload/"
MEDIA_ROOT = "/www/upload/simq/admin/upload/"


# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
DATA_UPLOAD_MAX_NUMBER_FIELDS = 200000
SESSION_COOKIE_NAME = "simqsvr_session_cookie_id"
CSRF_COOKIE_NAME = "simqsvr_csrf_cookie_id"
CSRF_COOKIE_HTTPONLY = True
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "INFO",
    },
    "loggers": {
        "django": {
            "handlers": ["console"],
            "level": "INFO",
            "propagate": False,
        },
        "django_apis": {
            "handlers": ["console"],
            "level": "INFO",
            "propagate": False,
        },
        "simq": {
            "handlers": ["console"],
            "level": "INFO",
            "propagate": False,
        },
        "simqsvr": {
            "handlers": ["console"],
            "level": "INFO",
            "propagate": False,
        },
    },
}


DJANGO_APIS_OPENAPI_TITLE = "simqsvr"
DJANGO_APIS_OPENAPI_DESCRIPTION = "simqsvr"
DJANGO_APIS_OPENAPI_VERSION = VERSION
DJANGO_APIS_OPENAPI_SECURITY_DEFINITIONS = {
    "username": {
        "type": "apiKey",
        "name": "TokenUsername",
        "in": "header",
    },
    "name": {
        "type": "apiKey",
        "name": "TokenUserRealName",
        "in": "header",
    },
    "department": {
        "type": "apiKey",
        "name": "TokenDepartmentName",
        "in": "header",
    },
}


from django_environ_settings import django_environ_settings_patch_all

django_environ_settings_patch_all()

try:
    from localsettings import *
except ImportError:
    pass

from django_app_requires import patch_all as django_app_requires_patch_all

django_app_requires_patch_all()

try:
    os.makedirs(STATIC_ROOT, exist_ok=True)
except Exception as error:
    _logger.warning(
        "Create STATIC_ROOT failed: STATIC_ROOT=%s, error=%s",
        STATIC_ROOT,
        error,
    )

try:
    os.makedirs(MEDIA_ROOT, exist_ok=True)
except Exception as error:
    _logger.warning(
        "Create MEDIA_ROOT failed: MEDIA_ROOT=%s, error=%s",
        MEDIA_ROOT,
        error,
    )
