"""
SDC Django settings extension for §PROJECT§.

Generated by '§PROJECT§' using SDC.

For more information on this file, see
https://simpledomcontrol.readthedocs.io/en/latest/
"""
import os
from urllib.parse import urlparse

from django.core.exceptions import ImproperlyConfigured

from §PROJECT§.base_settings import *


def _parse_allowed_host(value):
    # ALLOWED_HOST is a comma-separated list of site URLs, e.g. "https://example.com,https://www.example.com".
    # Entries without a scheme are read as https.
    urls = []
    for entry in value.split(','):
        entry = entry.strip()
        if entry:
            urls.append(urlparse(entry if '://' in entry else f'https://{entry}'))
    return urls


if not DEBUG:
    _hosts = _parse_allowed_host(os.environ.get('ALLOWED_HOST', ''))
    if not _hosts:
        raise ImproperlyConfigured(
            "Set the environment variable ALLOWED_HOST to the comma-separated URLs of this site "
            "(e.g. ALLOWED_HOST=https://example.com) when DEBUG is False.")
    ALLOWED_HOSTS = [host.hostname for host in _hosts]
    CSRF_TRUSTED_ORIGINS = [f'{host.scheme}://{host.netloc}' for host in _hosts]
    _default_home_url = f'{_hosts[0].scheme}://{_hosts[0].netloc}'
else:
    ALLOWED_HOSTS = ['*']
    _default_home_url = 'http://127.0.0.1:8000'

# Base URL used in links of e-mails (e.g. confirmation and password reset of sdc_user)
# when it cannot be taken from the request.
if 'HOME_URL' not in locals():
    HOME_URL = os.environ.get('HOME_URL', _default_home_url)

if 'VERSION' not in locals():
    VERSION = 0.0

# Add daphne amd SDC packages to installed apps
# (https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/daphne/)

INSTALLED_APPS = ['daphne'] + INSTALLED_APPS + ['channels', 'sdc_tools', 'sdc_user']

if 'INTERNAL_IPS' not in locals():
    INTERNAL_IPS = (
        '127.0.0.1',
    )

# DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

STATIC_ROOT = BASE_DIR / 'www/'

STATICFILES_DIRS = [BASE_DIR / "static", BASE_DIR / "node_modules"]

# Set ASGI root (https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/daphne/)

ASGI_APPLICATION = '§PROJECT§.asgi.application'

# Add jest database for SDC tests

DATABASES_AVAILABLE = {
                          'jest': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'test_db.sqlite3', },
                      } | DATABASES

database = os.environ.get('DJANGO_DATABASE', 'default')
if database not in DATABASES_AVAILABLE:
    raise ImproperlyConfigured(
        f"DJANGO_DATABASE={database!r} is not defined. Use one of: {', '.join(DATABASES_AVAILABLE)}")

# The selected database becomes the default one; other aliases of DATABASES are kept.
DATABASES = DATABASES | {'default': DATABASES_AVAILABLE[database]}

# Setup necessary template settings for SDC

TEMPLATES[0]["APP_DIRS"] = True
if BASE_DIR / "templates" not in TEMPLATES[0]["DIRS"]:
    TEMPLATES[0]["DIRS"].append(BASE_DIR / "templates")

if DEBUG:
    CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer"
        }
    }
else:
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels_redis.core.RedisChannelLayer',
            'CONFIG': {
                # NB: must be a dict (not a (host, port) tuple) so we can pass
                # socket_timeout. redis-py >= 8 defaults socket_timeout to 5s,
                # which exactly races channels-redis' hardcoded brpop_timeout=5,
                # raising "Timeout reading from redis" on every idle WebSocket
                # receive. Keep socket_timeout > brpop_timeout (5s) to avoid it.
                "hosts": [{"host": "redis", "port": 6379, "socket_timeout": 20}],
                "capacity": 1500,
                "expiry": 10,
            },
        },
    }

if 'MEDIA_URL' not in locals():
    MEDIA_URL = '/media/'

if 'MEDIA_ROOT' not in locals():
    MEDIA_ROOT = BASE_DIR / 'media'

SERVER_CALL_VIA_WEB_SOCKET = False
MODEL_FORM_TEMPLATE = "elements/form.html"
LOGIN_CONTROLLER = 'sdc-login'
LOGIN_SUCCESS = '/'

JWT = {'secret': SECRET_KEY, 'algorithm': 'HS256' , 'exp_delta_seconds': 3600}

AUTH_USER_MODEL = "sdc_user.SdcUser"

# Access rules of the SdcUser model. Both settings are dotted paths to functions:
#
# def sdc_user_get_queryset(sdc_user_cls, user, action, obj):
#     # Rows a user may load/edit. Default: all users for superusers, otherwise only the user itself.
#     return sdc_user_cls.objects.all() if user.is_superuser else sdc_user_cls.objects.filter(pk=user.pk)
#
# def sdc_user_is_authorised(user, action, obj):
#     # Whether a user may perform an action. Default: registration for everyone,
#     # read/edit for logged-in users, delete/upload for superusers only.
#     ...
SDC_USER_GET_QUERYSET = "sdc_user.models.sdc_user_get_queryset"
SDC_USER_IS_AUTHORISED = "sdc_user.models.sdc_user_is_authorised"
# Fields of SdcUser sent to clients. The password hash is never sent.
SDC_USER_FIELDS = "__all__"
SDC_USER_FIELDS_EXCLUDE = None
# If True, users (except superusers) can only log in after confirming their e-mail address.
SDC_USER_REQUIRE_CONFIRMED_EMAIL = False

# EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
# EMAIL_HOST =''
# EMAIL_PORT = 587
# EMAIL_HOST_USER = ''
# DEFAULT_FROM_EMAIL = ''
# EMAIL_HOST_PASSWORD = ''
# EMAIL_USE_TLS = True
