"""
Django settings for medux project.

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

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

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

import environ
from pathlib import Path
from gdaps.pluginmanager import PluginManager

# Initialise environment variables
env = environ.Env(
    # set casting, default value
    # DEBUG=(bool, False)
)

# First look in CWD for .env file, use it if if exists
# This is useful for plugin development in separate directories/virtualenvs
if Path(".env").exists():
    env.read_env(env_file=str(Path.cwd() / ".env"))
else:
    # if not, use the default location from django-environ
    env.read_env()

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

PROJECT_NAME = "medux"

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env(
    "SECRET_KEY", default="don't use this pseudo-secret-key on production!"
)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env("DEBUG", default=False)

# Beware: Django Debug Toolbar seems to have problems with Sockpuppet.
DEBUG_TOOLBAR = False


ALLOWED_HOSTS = env("ALLOWED_HOSTS", default="127.0.0.1,localhost").split(",")

# Application definition
INSTALLED_APPS = [
    "whitenoise.runserver_nostatic",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django_extensions",
    "django.forms",
    "crispy_forms",
    "crispy_bootstrap5",
    "gdaps",
    "django_htmx",
    # "django_filters",
    "medux.common",
    "medux.preferences",
    "component_tags",
    "composite_field",
]

SITE_ID = 1

if DEBUG_TOOLBAR:
    INSTALLED_APPS += ["debug_toolbar"]

# Note: Plugins that are included per default within this repository
# should be added to the [options.entry_points] section in MdeUX' setup.cfg
INSTALLED_APPS += PluginManager.find_plugins("medux.plugins")

# https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model
AUTH_USER_MODEL = "common.User"

MIDDLEWARE = []
if DEBUG_TOOLBAR:
    MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]

MIDDLEWARE += [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "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",
    "django.contrib.sites.middleware.CurrentSiteMiddleware",
    "django_htmx.middleware.HtmxMiddleware",
    "medux.core.middleware.DeviceMiddleware",
]

ROOT_URLCONF = "medux.urls"

# https://docs.djangoproject.com/en/dev/ref/settings/#login-url
LOGIN_URL = "/accounts/login/"
LOGIN_REDIRECT_URL = "home"
LOGOUT_REDIRECT_URL = "home"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "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",
            ],
            "builtins": ["component_tags.template.builtins"],
        },
    },
]
TEMPLATE_CONTEXT_PROCESSORS = ["django.core.context_processors.request"]
# https://docs.djangoproject.com/en/3.2/ref/settings/#std:setting-FORM_RENDERER
FORM_RENDERER = "django.forms.renderers.TemplatesSetting"


# Password validation
# https://docs.djangoproject.com/en/3.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",
    },
]

DATABASES = {
    "default": {
        "ENGINE": env("DATABASE_ENGINE", default="django.db.backends.sqlite3"),
        "NAME": env("DATABASE_NAME", default="medux.sqlite3"),
        "USER": env("DATABASE_USER", default=""),
        "PASSWORD": env("DATABASE_PASS", default=""),
    }
}

# https://docs.djangoproject.com/en/3.2/releases/3.2/#customizing-type-of-auto-created-primary-keys
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = "de-AT"

TIME_ZONE = "Europe/Vienna"

USE_I18N = True

USE_L10N = True

USE_TZ = True

LOCALE_PATHS = [BASE_DIR / "locale"]

# Static files (CSS, JavaScript, Images)
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "static"
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

MEDIA_ROOT = BASE_DIR / "media"

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"console": {"class": "logging.StreamHandler"}},
    "loggers": {
        "gdaps": {"handlers": ["console"], "level": "INFO", "propagate": True},
        "django": {"handlers": ["console"], "level": "INFO", "propagate": True},
        # "django.template": {
        #     "handlers": ["console"],
        #     "level": "DEBUG",
        #     "propagate": True,
        # },
        "unicorn": {"handlers": ["console"], "level": "INFO"},
        "medux": {"handlers": ["console"], "level": "DEBUG"},
    },
}


# GDAPS configuration
GDAPS = {}

CHANNEL_LAYERS = {
    "default": {
        # "BACKEND": "channels.layers.InMemoryChannelLayer",
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

ASGI_APPLICATION = "medux.asgi.application"

# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html
INTERNAL_IPS = ["127.0.0.1", "localhost"]

if DEBUG_TOOLBAR:
    DEBUG_TOOLBAR_PANELS = [
        "debug_toolbar.panels.history.HistoryPanel",
        "debug_toolbar.panels.versions.VersionsPanel",
        "debug_toolbar.panels.timer.TimerPanel",
        "debug_toolbar.panels.settings.SettingsPanel",
        "debug_toolbar.panels.headers.HeadersPanel",
        # 'debug_toolbar.panels.request.RequestPanel',  # remove due to problems with ASGI
        "debug_toolbar.panels.sql.SQLPanel",
        "debug_toolbar.panels.staticfiles.StaticFilesPanel",
        "debug_toolbar.panels.templates.TemplatesPanel",
        "debug_toolbar.panels.cache.CachePanel",
        "debug_toolbar.panels.signals.SignalsPanel",
        "debug_toolbar.panels.logging.LoggingPanel",
        "debug_toolbar.panels.redirects.RedirectsPanel",
        "debug_toolbar.panels.profiling.ProfilingPanel",
    ]


# REST_FRAMEWORK = {
#     "DEFAULT_PERMISSION_CLASSES": [
#       "rest_framework.permissions.DjangoModelPermissions"
#     ]
# }

MEDUX = {"BIRTHDAY_FORMAT": "Date"}

# django-crispy.forms
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"

if DEBUG:
    CACHES = {
        "default": {
            "BACKEND": "django.core.cache.backends.dummy.DummyCache",
        }
    }
