"""
Django settings for openlink project.

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

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 logging
import os

import environ
import ldap
from django.contrib.messages import constants as messages
from django.core.management.utils import get_random_secret_key
from django_auth_ldap.config import LDAPSearch

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False),
    AUTH_LDAP=(bool, False),
    AUTH_OIDC=(bool, False),
)

env_paths = [
    environ.Path("/etc/openlink/openlink.env"),
]

if env.str('OPENLINK_ENV_PATH', default='') != '':
    env_paths.insert(0, environ.Path(env.str('OPENLINK_ENV_PATH')))

# Read in any environment files
for e in env_paths:
    try:
        e.file("")
        env.read_env(e())
    except FileNotFoundError:
        pass


# 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 = env("SECRET_KEY", default=get_random_secret_key())

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

ALLOWED_HOSTS = ["localhost"]


# Application definition

INSTALLED_APPS = [
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "openlink.core",
    "django.contrib.admin",
    "crispy_forms",
    "django_filters",
    "widget_tweaks",
    "django_extensions",
    "django_json_ld",
    "popup_forms",
    "rest_framework",
    "django_rq",
    "guardian",
    "ckeditor",
    "debug_toolbar",
]

default_connectors = [
    'openlink.connectors.openlink_labguru',
    'openlink.connectors.openlink_omero',
    'openlink.connectors.openlink_seafile',
    'openlink.connectors.openlink_ssh',
    'openlink.connectors.openlink_zenodo'
]

INSTALLED_CONNECTORS = env.list("INSTALLED_CONNECTORS", default=default_connectors)
INSTALLED_APPS.extend(INSTALLED_CONNECTORS)

RQ_SHOW_ADMIN_LINK = True
RQ_QUEUES = {
    "default": {
        "HOST": "localhost",
        "PORT": 6379,
        "DB": 0,
    },
}

CRISPY_TEMPLATE_PACK = "bootstrap4"

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",
    "debug_toolbar.middleware.DebugToolbarMiddleware",
]

ROOT_URLCONF = "openlink.urls"

LOGIN_REDIRECT_URL = "/projects"


MESSAGE_TAGS = {
    messages.ERROR: "danger",
}

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(BASE_DIR, "openlink/templates"),
            os.path.join(BASE_DIR, "openlink/core/lib/tools/templates"),  # type: ignore
            os.path.join(BASE_DIR, "openlink/core/templates"),  # type: ignore
        ],
        "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",
            ],
            "libraries": {
                "split_tags": "openlink.core.templatetags.split",
                "param_tags": "openlink.core.templatetags.param",
                "url_link_tags": "openlink.core.templatetags.url_link",
                "humansize": "openlink.core.templatetags.humansize",
                "contains_assay_tags": "openlink.core.templatetags.contains_assay",
                "get_version": "openlink.core.templatetags.get_version",
                "plurals_type": "openlink.core.templatetags.plurals_type",
                "has_access_url": "openlink.core.templatetags.has_access_url",
                "get_oidc": "openlink.core.templatetags.get_oidc",
            },
        },
    },
]

WSGI_APPLICATION = "openlink.wsgi.application"


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

if env.str('DATABASE_URL', default=''):
    DATABASES = {
        'default': env.db(),
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, "db.sqlite3"),
        },
    }

# 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/

LANGUAGE_CODE = "en-us"

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 = "/static/"
STATIC_ROOT = ".static"

INTERNAL_IPS = ("127.0.0.1",)

GRAPH_MODELS = {
    "all_applications": True,
    "group_models": True,
}

AUTH_PROFILE_MODULE = "openlink.core.profile"

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "filters": {
        "require_debug_true": {
            "()": "django.utils.log.RequireDebugTrue",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "filters": ["require_debug_true"],
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "DEBUG",
    },
    "loggers": {
        "mylogger": {
            "handlers": ["console"],
            "level": os.getenv("DJANGO_LOG_LEVEL", "INFO"),
            "propagate": True,
        },
    },
}


REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly"
    ]
}

AUTHENTICATION_BACKENDS = [
    "mozilla_django_oidc.auth.OIDCAuthenticationBackend",
    "django_auth_ldap.backend.LDAPBackend",
    "django.contrib.auth.backends.ModelBackend",
    "guardian.backends.ObjectPermissionBackend",
]

AUTH_LDAP = env("AUTH_LDAP")
if AUTH_LDAP:
    AUTH_LDAP_SERVER_URI = env("AUTH_LDAP_SERVER_URI")
    AUTH_LDAP_BIND_DN = env("AUTH_LDAP_BIND_DN")
    AUTH_LDAP_BIND_PASSWORD = env("AUTH_LDAP_BIND_PASSWORD")
    AUTH_LDAP_USER_SEARCH = LDAPSearch(
        env("AUTH_LDAP_SEARCH"), ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
    )
    AUTH_LDAP_USER_ATTR_MAP = env.json("AUTH_LDAP_USER_ATTR_MAP")

AUTH_OIDC = env("AUTH_OIDC")
if AUTH_OIDC:
    OIDC_RP_CLIENT_ID = env("OIDC_RP_CLIENT_ID")
    OIDC_RP_CLIENT_SECRET = env("OIDC_RP_CLIENT_SECRET")
    OIDC_OP_AUTHORIZATION_ENDPOINT = env("OIDC_OP_AUTHORIZATION_ENDPOINT")
    OIDC_OP_TOKEN_ENDPOINT = env("OIDC_OP_TOKEN_ENDPOINT")
    OIDC_OP_USER_ENDPOINT = env("OIDC_OP_USER_ENDPOINT")
    OIDC_RP_SIGN_ALGO = env("OIDC_RP_SIGN_ALGO")
    OIDC_OP_JWKS_ENDPOINT = env("OIDC_OP_JWKS_ENDPOINT")


# AUTHENTICATION_BACKENDS = [
#     "django_auth_ldap.backend.LDAPBackend",
#     "django.contrib.auth.backends.ModelBackend", ]

# AUTH_LDAP_SERVER_URI = ""
# AUTH_LDAP_BIND_DN = ""

# AUTH_LDAP_BIND_PASSWORD = ""

# AUTH_LDAP_USER_SEARCH = LDAPSearch(

#     "ou=Utilisateurs,dc=igbmc,dc=u-strasbg,dc=fr", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"

# )

# AUTH_LDAP_USER_ATTR_MAP = {
#     "first_name": "givenName",
#     "last_name": "sn",
#     "email": "mail",
# }

logger = logging.getLogger("django_auth_ldap")
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

CKEDITOR_CONFIGS = {
    "zenodo": {
        "toolbar": "zenodo",
        "toolbar_zenodo": [
            {
                "name": "clipboard",
                "items": [
                    "PasteText",
                    "PasteFromWord",
                ],
            },
            {
                "name": "basicstyles",
                "items": [
                    "Bold",
                    "Italic",
                    "Strike",
                    "Subscript",
                    "Superscript",
                    "-",
                ],
            },
            {
                "name": "links",
                "items": [
                    "Link",
                    "Unlink",
                ],
            },
            {
                "name": "paragraph",
                "items": [
                    "NumberedList",
                    "BulletedList",
                    "Outdent",
                    "Indent",
                    "Blockquote",
                    "CodeSnippet",
                ],
            },
            {
                "name": "undo",
                "groups": ["clipboard", "undo"],
                "items": ["Undo", "Redo", "RemoveFormat"],
            },
            {"name": "insert", "items": ["SpecialChar", "Mathjax"]},
            {"name": "document", "items": ["Source"]},
            {
                "name": "tools",
                "items": [
                    "Maximize",
                ],
            },
        ],
        "extraPlugins": "codesnippet,mathjax",
        "mathJaxLib": "//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML",
        "height": "100%",
        "width": "100%",
    },
}
