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

"""

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

from django.contrib.messages import constants as messages
from gvacommon.settings_utils import get_env_variable

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

# Site name:
SITE_NAME = basename(DJANGO_ROOT)

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

GVA_ENVIRONMENT = get_env_variable("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 = (
    (
        get_env_variable("GVA_ADMIN_NAME", default="Admin"),
        get_env_variable("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": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": get_env_variable("GVA_PGSQL_DATABASE", default="gnuviechadmin"),
        "USER": get_env_variable("GVA_PGSQL_USER", default="gnuviechadmin"),
        "PASSWORD": get_env_variable("GVA_PGSQL_PASSWORD"),
        "HOST": get_env_variable("GVA_PGSQL_HOSTNAME", default="db"),
        "PORT": get_env_variable("GVA_PGSQL_PORT", int, default=5432),
    }
}

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 = get_env_variable("GVA_DOMAIN_NAME")
SITES_SITE_NAME = get_env_variable("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 = get_env_variable("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",
    "django.middleware.locale.LocaleMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    # uncomment next line to enable translation to browser locale
    "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": get_env_variable("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 = get_env_variable(
    "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 = get_env_variable(
    "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 = get_env_variable("GVA_MIN_OS_UID", int, default=10000)
OSUSER_MINGID = get_env_variable("GVA_MIN_OS_GID", int, default=10000)
OSUSER_USERNAME_PREFIX = get_env_variable("GVA_OSUSER_PREFIX", default="usr")
OSUSER_HOME_BASEPATH = get_env_variable("GVA_OSUSER_HOME_BASEPATH", default="/home")
OSUSER_DEFAULT_SHELL = get_env_variable(
    "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 = get_env_variable("GVA_OSUSER_UPLOADSERVER", default="file")

GVA_LINK_WEBMAIL = get_env_variable(
    "GVA_WEBMAIL_URL", default="https://webmail.example.org/"
)
GVA_LINK_PHPMYADMIN = get_env_variable(
    "GVA_PHPMYADMIN_URL", default="https://phpmyadmin.example.org/"
)
GVA_LINK_PHPPGADMIN = get_env_variable(
    "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 = "/srv/gva/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 = get_env_variable(
        "GVA_SITE_ADMINMAIL", default="admin@example.org"
    )

    # See: https://docs.djangoproject.com/en/dev/ref/settings/#server-email
    SERVER_EMAIL = get_env_variable("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