"""
Django settings for core project.

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

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

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

import os

from django.utils.translation import gettext_lazy as _
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from ruamel.yaml import YAML

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ENVIRONMENT = os.getenv("ENVIRONMENT", "LOCAL")
VARS_PATH = os.getenv("VARS_PATH", BASE_DIR + "/vars_path")
VARS_PATH_FILENAME = os.getenv("VARS_PATH_FILENAME", "secrets.yml")
with open(f"{VARS_PATH}{os.path.sep}{VARS_PATH_FILENAME}", "r") as secrets_file:
    secrets_content = secrets_file.read()
    yaml = YAML(typ="safe")
    SECRETS_SAFE = yaml.load(secrets_content)

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = SECRETS_SAFE.get("secret_key", "mysuperkey")

# SECURITY WARNING: don't run with debug turned on in production!
if ENVIRONMENT in ['STG', 'PRD']:
    DEBUG = False
else:
    DEBUG = True

ALLOWED_HOSTS = SECRETS_SAFE.get("allowed_hosts", [])

# Application definition

INSTALLED_APPS = [
    'db.apps.DbConfig',
    'api.apps.ApiConfig',
    'web.apps.WebConfig',
    'editorjs.apps.EditorjsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'debug_toolbar',
    'phonenumber_field',
    'graphene_django',
    'precise_bbcode',
    'qr_code',
    'django_otp',
    'django_otp.plugins.otp_totp',
    'django_otp.plugins.otp_hotp',
    'django_otp.plugins.otp_static',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django_otp.middleware.OTPMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 'debug_toolbar.middleware.DebugToolbarMiddleware',
    'web.middlewares.MusesParams',
    'web.middlewares.MusesPagesViews'
]

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            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',
                'web.context_processors.global_context',
                'web.context_processors.sections'
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'

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

if ENVIRONMENT in ['CI']:
    """ TODO: """
elif ENVIRONMENT in ['DEV', 'STG', 'PRD']:
    """ TODO: """
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Authentication User Model
AUTH_USER_MODEL = "db.Member"

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

LOCALE_PATHS = [
    BASE_DIR + '/api/locale',
    BASE_DIR + '/core/locale',
    BASE_DIR + '/db/locale',
    BASE_DIR + '/web/locale'
]

LANGUAGES = [
    ('fr', _('French')),
    ('fr-ca', _('Canadian French')),
    ('en-us', _('English'))
]

LANGUAGE_CODE = SECRETS_SAFE.get("language_code", "fr")

TIME_ZONE = SECRETS_SAFE.get("time_zone", "Europe/Paris")

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = SECRETS_SAFE.get("static_url", "http://127.0.0.1:8001/")
STATIC_ROOT = SECRETS_SAFE.get("staticfiles_path", f"{BASE_DIR}/static/")
MEDIA_URL = SECRETS_SAFE.get("media_url", "http://127.0.0.1:8002/")
MEDIA_ROOT = SECRETS_SAFE.get("media_path", f"{BASE_DIR}/media/")

GRAPHENE = {
    'SCHEMA': 'core.schema.schema'
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': f"{BASE_DIR}/logs/debug.log",
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django.db.backends.schema': {
            'handlers': [
                'console'
            ],
            'propagate': True,
            'level': 'INFO',
        },
        'django.request': {
            'handlers': [
                'console'
            ],
            'level': 'ERROR',
            'propagate': False,
        },
        'django': {
            'handlers': [
                'console',
                # 'file'
            ],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

MUSES = {
    "ADMINISTRATORS_GROUP": "muses_administrators",
    "MODERATORS_GROUP": "muses_moderators",
    "CORRECTORS_GROUP": "muses_correctors"
}

GOOGLE_CLIENT_ID = ""

# SHOW_TOOLBAR_CALLBACK = 'debug_toolbar.middleware.show_toolbar'
#
# INTERNAL_IPS = [
#     '127.0.0.1',
# ]

EMAIL_HOST = SECRETS_SAFE.get("smtp_server", "localhost")
EMAIL_PORT = SECRETS_SAFE.get("smtp_port", 25)
EMAIL_HOST_USER = SECRETS_SAFE.get("smtp_user", "")
EMAIL_HOST_PASSWORD = SECRETS_SAFE.get("smtp_password", "")
EMAIL_USE_TLS = SECRETS_SAFE.get("use_tls", False)
EMAIL_USE_SSL = SECRETS_SAFE.get("use_ssfreel", False)
