# -*- python -*-
# pymode:lint_ignore=E501
"""
Common settings and globals.

"""

from os.path import abspath, basename, dirname, join, normpath
from environs import Env

from django.contrib.messages import constants as messages

env = Env()
env.read_env()

# ######### PATH CONFIGURATION
# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))

# Absolute filesystem path to the top-level project folder:
SITE_ROOT = dirname(DJANGO_ROOT)

ROOT_DIR = dirname(DJANGO_ROOT)

# Site name:
SITE_NAME = basename(DJANGO_ROOT)

# ######### END PATH CONFIGURATION

GVA_ENVIRONMENT = env.str("GVA_ENVIRONMENT", default="prod")

# ######### DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = GVA_ENVIRONMENT == "local"
# ######### END DEBUG CONFIGURATION


# ######### MANAGER CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = (
    (
        env.str("GVA_ADMIN_NAME", default="Admin"),
        env.str("GVA_ADMIN_EMAIL", default="admin@example.org"),
    ),
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# ######### END MANAGER CONFIGURATION


# ######### DATABASE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
    "default": env.dj_db_url("GVA_DATABASE_URL"),
}

DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
# ######### END DATABASE CONFIGURATION


# ######### GENERAL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
TIME_ZONE = "Europe/Berlin"

# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = "en-us"

# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
SITES_DOMAIN_NAME = env.str("GVA_DOMAIN_NAME")
SITES_SITE_NAME = env.str("GVA_SITE_NAME")

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
# ######### END GENERAL CONFIGURATION


LOCALE_PATHS = (normpath(join(SITE_ROOT, "gnuviechadmin", "locale")),)

# ######### MEDIA CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = normpath(join(SITE_ROOT, "media"))

# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = "/media/"
# ######### END MEDIA CONFIGURATION


# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = "/static/"

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS  # noqa
STATICFILES_DIRS = (normpath(join(SITE_ROOT, "gnuviechadmin", "static")),)

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders  # noqa
STATICFILES_FINDERS = (
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
)
# ######### END STATIC FILE CONFIGURATION


# ######### SECRET CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Note: This key should only be used for development and testing.
SECRET_KEY = env.str("GVA_SITE_SECRET")
# ######### END SECRET CONFIGURATION


# ######### SITE CONFIGURATION
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# ######### END SITE CONFIGURATION


# ######### FIXTURE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS  # noqa
FIXTURE_DIRS = (normpath(join(SITE_ROOT, "fixtures")),)
# ######### END FIXTURE CONFIGURATION


# ######### TEMPLATE CONFIGURATION
# See: https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-TEMPLATES  # noqa
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [normpath(join(DJANGO_ROOT, "templates"))],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.contrib.auth.context_processors.auth",
                "django.template.context_processors.debug",
                "django.template.context_processors.i18n",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
                "django.template.context_processors.tz",
                "django.contrib.messages.context_processors.messages",
                "django.template.context_processors.request",
                # custom context processors
                "gnuviechadmin.context_processors.navigation",
                "gnuviechadmin.context_processors.version_info",
            ]
        },
    }
]
# ######### END TEMPLATE CONFIGURATION


# ######### MIDDLEWARE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes
MIDDLEWARE = [
    # Default Django middleware.
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "allauth.account.middleware.AccountMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]
# ######### END MIDDLEWARE CONFIGURATION


AUTHENTICATION_BACKENDS = (
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",
    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)

# ######### URL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = "%s.urls" % SITE_NAME
# ######### END URL CONFIGURATION


# ######### TEST RUNNER CONFIGURATION
TEST_RUNNER = "django.test.runner.DiscoverRunner"
# ######### END TEST RUNNER CONFIGURATION


# ######### APP CONFIGURATION
DJANGO_APPS = (
    # Default Django apps:
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # Useful template tags:
    "django.contrib.humanize",
    # Admin panel and documentation:
    "django.contrib.admin",
    # Flatpages for about page
    "django.contrib.flatpages",
    "crispy_forms",
    "crispy_bootstrap5",
    "impersonate",
    "rest_framework",
    "rest_framework.authtoken",
)

ALLAUTH_APPS = (
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
    "allauth.socialaccount.providers.linkedin_oauth2",
)

# Apps specific for this project go here.
LOCAL_APPS = (
    "dashboard",
    "taskresults",
    "ldaptasks",
    "mysqltasks",
    "pgsqltasks",
    "fileservertasks",
    "webtasks",
    "domains",
    "osusers",
    "managemails",
    "userdbs",
    "hostingpackages",
    "websites",
    "help",
    "invoices",
    "contact_form",
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + ALLAUTH_APPS + LOCAL_APPS

MESSAGE_TAGS = {
    messages.DEBUG: "",
    messages.ERROR: "alert-danger",
    messages.INFO: "alert-info",
    messages.SUCCESS: "alert-success",
    messages.WARNING: "alert-warning",
}
# ######### END APP CONFIGURATION


# ######### ALLAUTH CONFIGURATION
ACCOUNT_ADAPTER = "gnuviechadmin.auth.NoNewUsersAccountAdapter"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
LOGIN_REDIRECT_URL = "/"
SOCIALACCOUNT_AUTO_SIGNUP = False
SOCIALACCOUNT_QUERY_EMAIL = True
# ######### END ALLAUTH CONFIGURATION


# ######### CRISPY FORMS CONFIGURATION
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"
# ######### END CRISPY_FORMS CONFIGURATION


# ######### REST FRAMEWORK CONFIGURATION
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.BasicAuthentication",
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
    ],
    "DEFAULT_RENDERER_CLASSES": [
        "rest_framework.renderers.JSONRenderer",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAdminUser",
    ],
}
# ######### END REST FRAMEWORK CONFIGURATION


# ######### LOGGING CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "%(levelname)s %(asctime)s %(name)s "
            "%(module)s:%(lineno)d %(process)d %(thread)d %(message)s"
        },
        "simple": {"format": "%(levelname)s %(name)s:%(lineno)d %(message)s"},
    },
    "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
        },
        "logfile": {
            "level": "INFO",
            "class": "logging.FileHandler",
            "filename": env.str("GVA_LOG_FILE", default="gva.log"),
            "formatter": "verbose",
        },
        "mail_admins": {
            "level": "ERROR",
            "filters": ["require_debug_false"],
            "class": "django.utils.log.AdminEmailHandler",
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "WARNING",
    },
    "loggers": {
        "django.request": {
            "handlers": ["mail_admins"],
            "level": "ERROR",
            "propagate": True,
        },
        "django": {
            "handlers": ["logfile"],
            "level": "INFO",
            "propagate": False,
        },
    },
}

for app in LOCAL_APPS:
    LOGGING["loggers"][app] = {
        "handlers": ["logfile"],
        "level": "INFO",
        "propagate": False,
    }
# ######### END LOGGING CONFIGURATION


# ######### WSGI CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = "%s.wsgi.application" % SITE_NAME
# ######### END WSGI CONFIGURATION


# ######### CELERY CONFIGURATION
BROKER_URL = env.str(
    "GVA_BROKER_URL", default="amqp://gnuviechadmin:gnuviechadmin@mq/gnuviechadmin"
)
BROKER_TRANSPORT_OPTIONS = {
    "max_retries": 3,
    "interval_start": 0,
    "interval_step": 0.2,
    "interval_max": 0.2,
}
CELERY_RESULT_BACKEND = env.str(
    "GVA_RESULTS_REDIS_URL", default="redis://:gnuviechadmin@redis:6379/0"
)
CELERY_TASK_RESULT_EXPIRES = None
CELERY_ROUTES = ("gvacommon.celeryrouters.GvaRouter",)
CELERY_TIMEZONE = "Europe/Berlin"
CELERY_ENABLE_UTC = True
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = "json"
# ######### END CELERY CONFIGURATION


# ######### CUSTOM APP CONFIGURATION
OSUSER_MINUID = env.int("GVA_MIN_OS_UID", default=10000)
OSUSER_MINGID = env.int("GVA_MIN_OS_GID", default=10000)
OSUSER_USERNAME_PREFIX = env.str("GVA_OSUSER_PREFIX", default="usr")
OSUSER_HOME_BASEPATH = env.str("GVA_OSUSER_HOME_BASEPATH", default="/home")
OSUSER_DEFAULT_SHELL = env.str("GVA_OSUSER_DEFAULT_SHELL", default="/usr/bin/rssh")
OSUSER_SFTP_GROUP = "sftponly"
OSUSER_SSH_GROUP = "sshusers"
OSUSER_DEFAULT_GROUPS = [OSUSER_SFTP_GROUP]
OSUSER_UPLOAD_SERVER = env.str("GVA_OSUSER_UPLOADSERVER", default="file")

GVA_LINK_WEBMAIL = env.str("GVA_WEBMAIL_URL", default="https://webmail.example.org/")
GVA_LINK_PHPMYADMIN = env.str(
    "GVA_PHPMYADMIN_URL", default="https://phpmyadmin.example.org/"
)
GVA_LINK_PHPPGADMIN = env.str(
    "GVA_PHPPGADMIN_URL", default="https://phppgadmin.example.org/"
)
# ######### END CUSTOM APP CONFIGURATION

# ######### STATIC FILE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = env.str("GVA_STATIC_PATH", default=normpath(join(ROOT_DIR, "static")))


def show_debug_toolbar(request):
    return DEBUG and GVA_ENVIRONMENT == "local"


# ######### TOOLBAR CONFIGURATION
# See: http://django-debug-toolbar.readthedocs.org/en/latest/installation.html#explicit-setup # noqa
INSTALLED_APPS += ("debug_toolbar",)

MIDDLEWARE += [
    "impersonate.middleware.ImpersonateMiddleware",
    "debug_toolbar.middleware.DebugToolbarMiddleware",
]

DEBUG_TOOLBAR_CONFIG = {
    "SHOW_TOOLBAR_CALLBACK": "gnuviechadmin.settings.show_debug_toolbar"
}
# ######### END TOOLBAR CONFIGURATION


if GVA_ENVIRONMENT == "local":
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
    TEMPLATES[0]["OPTIONS"]["debug"] = DEBUG
    # ######### END DEBUG CONFIGURATION

    # ######### EMAIL CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
    EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
    # ######### END EMAIL CONFIGURATION

    # ######### CACHE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
    CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
    # ######### END CACHE CONFIGURATION

    LOGGING["handlers"].update(
        {
            "console": {
                "level": "DEBUG",
                "class": "logging.StreamHandler",
                "formatter": "simple",
            }
        }
    )
    LOGGING["loggers"].update(
        dict(
            [
                (key, {"handlers": ["console"], "level": "DEBUG", "propagate": True})
                for key in LOCAL_APPS
            ],
        )
    )
elif GVA_ENVIRONMENT == "test":
    ALLOWED_HOSTS = ["localhost"]
    PASSWORD_HASHERS = ("django.contrib.auth.hashers.MD5PasswordHasher",)
    LOGGING["handlers"].update(
        {
            "console": {
                "level": "ERROR",
                "class": "logging.StreamHandler",
                "formatter": "simple",
            }
        }
    )
    LOGGING["loggers"].update(
        dict(
            [
                (key, {"handlers": ["console"], "level": "ERROR", "propagate": True})
                for key in LOCAL_APPS
            ]
        )
    )
    LOGGING["loggers"]["django"] = {
        "handlers": ["console"],
        "level": "CRITICAL",
        "propagate": True,
    }
    BROKER_URL = BROKER_URL + "_test"
    CELERY_RESULT_PERSISTENT = False
else:
    # ######### HOST CONFIGURATION
    # See: https://docs.djangoproject.com/en/1.5/releases/1.5/#allowed-hosts-required-in-production # noqa
    ALLOWED_HOSTS = [SITES_DOMAIN_NAME]
    # ######### END HOST CONFIGURATION

    # ######### EMAIL CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
    EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix
    EMAIL_SUBJECT_PREFIX = "[%s] " % SITE_NAME

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email
    DEFAULT_FROM_EMAIL = env.str("GVA_SITE_ADMINMAIL", default="admin@example.org")

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#server-email
    SERVER_EMAIL = env.str("GVA_SITE_ADMINMAIL", default="admin@example.org")
    # ######### END EMAIL CONFIGURATION

    # ######### CACHE CONFIGURATION
    # See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
    # CACHES = {}
    # ######### END CACHE CONFIGURATION

    # ######### ALLAUTH PRODUCTION CONFIGURATION
    ACCOUNT_EMAIL_SUBJECT_PREFIX = "[Jan Dittberner IT-Consulting & -Solutions] "
    ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https"
    # ######### END ALLAUTH PRODUCTION CONFIGURATION
