"""
Django settings for project.

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

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

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

import os
import signal

from django.conf import settings

# make gettext work in settings.py
# https://github.com/DNX/django-simple-project/wiki/Translate-strings-in-settings.py
gettext = lambda s: s

from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured

# a convenient shortcut to import environment variables
env = os.environ.get
true_values = ['1', 'true', 'y', 'yes', 'on', 1, True]


# this is a custom method to import required env variables
def require_env(name):
    value = env(name)
    if not value:
        raise Exception('Missing {} env variable'.format(name))
    return value


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

BASE_URL = env('BASE_URL', 'http://localhost:8000')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DJANGO_DEBUG', 'True').lower() in true_values

# this env is set from the deploy script
if env('DJANGO_ALLOWED_HOSTS_STRING', False):
    ALLOWED_HOSTS = str(env('DJANGO_ALLOWED_HOSTS_STRING')).strip('"').split()
else:
    ALLOWED_HOSTS = ["127.0.0.1", "0.0.0.0", 'localhost']

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('DJANGO_SECRET_KEY', '123')

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'corsheaders',
    'rest_framework',
    'dry_rest_permissions',
    'api',
    'neo_backend',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    '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.middleware.locale.LocaleMiddleware',
]

ROOT_URLCONF = 'urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': env('DB_ENGINE', 'django.db.backends.sqlite3'),
        'NAME': env('DB_NAME', 'db.sqlite3'),
        'USER': env('DB_USER', ""),
        'PASSWORD': env('DB_PASSWORD', ""),
        'HOST': env('DB_HOST', "localhost"),
        'PORT': env('DB_PORT', ""),
    }
}

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


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

# marked as optional in the doc but seems to be necessary for this setup
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

LANGUAGE_CODE = 'de-ch'
LANGUAGES = (
    ('de', _('German')),
    ('en', _('English')),
)
TIME_ZONE = env('TIME_ZONE_IDENTIFIER', 'Europe/Zurich')
USE_I18N = True
USE_L10N = True
USE_TZ = True

DATE_INPUT_FORMATS = [
    '%d.%m.%Y', '%d.%m.%y',  # European
    '%Y-%m-%d',  # ISO (for native mobile datepickers)
    '%m/%d/%Y', '%m/%d/%y',  # US
    '%d %b %Y', '%d %B %Y',  # some long formats
]

TIME_INPUT_FORMATS = [
    '%H:%M',  # '14:30'
    '%H:%M:%S',  # '14:30:59'
    '%H:%M:%S.%f',  # '14:30:59.000200'
]

DATE_FORMAT = 'j F Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'j F Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'j N Y'
SHORT_DATETIME_FORMAT = 'j N Y H:i'
FIRST_DAY_OF_WEEK = 1

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = env('STATIC_ROOT', os.path.join(BASE_DIR, 'static-collected'))

MEDIA_URL = '/media/'
MEDIA_ROOT = env('MEDIA_ROOT', os.path.join(BASE_DIR, 'media/'))

# email stuff
BUSINESS_EMAIL = env('BUSINESS_EMAIL', "<EMAIL>")
BUSINESS_NAME = env('BUSINESS_NAME', "Business Name")
BUSINESS_EMAIL_VANE = "%(name)s <%(address)s>" % {"name": "{} Support Team".format(BUSINESS_NAME),
                                                  "address": BUSINESS_EMAIL}
DEFAULT_FROM_EMAIL = BUSINESS_EMAIL_VANE
EMAIL_BACKEND = env('EMAIL_BACKEND', 'django.core.mail.backends.dummy.EmailBackend')
EMAIL_HOST = env('EMAIL_HOST', '')
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD', '')
EMAIL_HOST_USER = env('EMAIL_HOST_USER', '')
EMAIL_PORT = env('EMAIL_PORT', '')
EMAIL_USE_TLS = env('EMAIL_USE_TLS', False)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'root': {
        'level': 'DEBUG',
        'handlers': ['console', 'file'],
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
        'file': {
            'level': 'DEBUG',
            # https://docs.python.org/3/library/logging.handlers.html
            # because of https://justinmontgomery.com/rotating-logs-with-multiple-workers-in-django
            'class': 'logging.handlers.WatchedFileHandler',
            'filename': env('LOGFILE', os.path.join(BASE_DIR, 'default.log')),
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

HTTPS = env('HTTPS', 'false').lower() in true_values

if HTTPS:
    PROTOCOL = 'https'
else:
    PROTOCOL = 'http'

# so that the auth migration files can be part of the project files, resolves stupid PSA bug / legacy thing
MIGRATION_MODULES = {
    # this is python social auth
    'default': 'external_migrations',
}

# there is no username field anymore
# USER_FIELDS = ['email']
# AUTH_USER_MODEL = "usermgmt.User"

# DRF

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        # 'rest_framework_csv.renderers.CSVRenderer',
    ),
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        # 'api.auth.TokenAuthSupportQueryString',
    ),
    # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    # 'PAGE_SIZE': 10,
    # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    # 'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S.%fZ",
    'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S",
}

# frontends wont work without CORS headers
if DEBUG:
    CORS_ORIGIN_ALLOW_ALL = True
else:
    CORS_ORIGIN_WHITELIST = tuple(ALLOWED_HOSTS) + tuple(str(env('DJANGO_CORS_ORIGIN_WHITELIST')).strip('"').split())


ENVIRONMENT = env('DJANGO_ENV', 'develop')
SENTRY_IS_ENABLED = env('SENTRY_IS_ENABLED', 'false').lower() in true_values


"""
Django settings for project.

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

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

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

import os
import signal

from django.conf import settings

# make gettext work in settings.py
# https://github.com/DNX/django-simple-project/wiki/Translate-strings-in-settings.py
gettext = lambda s: s

from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured

# a convenient shortcut to import environment variables
env = os.environ.get
true_values = ['1', 'true', 'y', 'yes', 'on', 1, True]


# this is a custom method to import required env variables
def require_env(name):
    value = env(name)
    if not value:
        raise Exception('Missing {} env variable'.format(name))
    return value


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

BASE_URL = env('BASE_URL', 'http://localhost:8000')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DJANGO_DEBUG', 'True').lower() in true_values

# this env is set from the deploy script
if env('DJANGO_ALLOWED_HOSTS_STRING', False):
    ALLOWED_HOSTS = str(env('DJANGO_ALLOWED_HOSTS_STRING')).strip('"').split()
else:
    ALLOWED_HOSTS = ["127.0.0.1", "0.0.0.0", 'localhost']

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('DJANGO_SECRET_KEY', '123')

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'corsheaders',
    'rest_framework',
    'dry_rest_permissions',
    'api',
    'neo_backend',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    '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.middleware.locale.LocaleMiddleware',
]

ROOT_URLCONF = 'urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': env('DB_ENGINE', 'django.db.backends.sqlite3'),
        'NAME': env('DB_NAME', 'db.sqlite3'),
        'USER': env('DB_USER', ""),
        'PASSWORD': env('DB_PASSWORD', ""),
        'HOST': env('DB_HOST', "localhost"),
        'PORT': env('DB_PORT', ""),
    }
}

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


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

# marked as optional in the doc but seems to be necessary for this setup
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

LANGUAGE_CODE = 'de-ch'
LANGUAGES = (
    ('de', _('German')),
    ('en', _('English')),
)
TIME_ZONE = env('TIME_ZONE_IDENTIFIER', 'Europe/Zurich')
USE_I18N = True
USE_L10N = True
USE_TZ = True

DATE_INPUT_FORMATS = [
    '%d.%m.%Y', '%d.%m.%y',  # European
    '%Y-%m-%d',  # ISO (for native mobile datepickers)
    '%m/%d/%Y', '%m/%d/%y',  # US
    '%d %b %Y', '%d %B %Y',  # some long formats
]

TIME_INPUT_FORMATS = [
    '%H:%M',  # '14:30'
    '%H:%M:%S',  # '14:30:59'
    '%H:%M:%S.%f',  # '14:30:59.000200'
]

DATE_FORMAT = 'j F Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'j F Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'j N Y'
SHORT_DATETIME_FORMAT = 'j N Y H:i'
FIRST_DAY_OF_WEEK = 1

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = env('STATIC_ROOT', os.path.join(BASE_DIR, 'static-collected'))

MEDIA_URL = '/media/'
MEDIA_ROOT = env('MEDIA_ROOT', os.path.join(BASE_DIR, 'media/'))

# email stuff
BUSINESS_EMAIL = env('BUSINESS_EMAIL', "<EMAIL>")
BUSINESS_NAME = env('BUSINESS_NAME', "Business Name")
BUSINESS_EMAIL_VANE = "%(name)s <%(address)s>" % {"name": "{} Support Team".format(BUSINESS_NAME),
                                                  "address": BUSINESS_EMAIL}
DEFAULT_FROM_EMAIL = BUSINESS_EMAIL_VANE
EMAIL_BACKEND = env('EMAIL_BACKEND', 'django.core.mail.backends.dummy.EmailBackend')
EMAIL_HOST = env('EMAIL_HOST', '')
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD', '')
EMAIL_HOST_USER = env('EMAIL_HOST_USER', '')
EMAIL_PORT = env('EMAIL_PORT', '')
EMAIL_USE_TLS = env('EMAIL_USE_TLS', False)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'root': {
        'level': 'DEBUG',
        'handlers': ['console', 'file'],
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
        'file': {
            'level': 'DEBUG',
            # https://docs.python.org/3/library/logging.handlers.html
            # because of https://justinmontgomery.com/rotating-logs-with-multiple-workers-in-django
            'class': 'logging.handlers.WatchedFileHandler',
            'filename': env('LOGFILE', os.path.join(BASE_DIR, 'default.log')),
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

HTTPS = env('HTTPS', 'false').lower() in true_values

if HTTPS:
    PROTOCOL = 'https'
else:
    PROTOCOL = 'http'

# so that the auth migration files can be part of the project files, resolves stupid PSA bug / legacy thing
MIGRATION_MODULES = {
    # this is python social auth
    'default': 'external_migrations',
}

# there is no username field anymore
# USER_FIELDS = ['email']
# AUTH_USER_MODEL = "usermgmt.User"

# DRF

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        # 'rest_framework_csv.renderers.CSVRenderer',
    ),
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        # 'api.auth.TokenAuthSupportQueryString',
    ),
    # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    # 'PAGE_SIZE': 10,
    # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    # 'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S.%fZ",
    'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S",
}

# frontends wont work without CORS headers
if DEBUG:
    CORS_ORIGIN_ALLOW_ALL = True
else:
    CORS_ORIGIN_WHITELIST = tuple(ALLOWED_HOSTS) + tuple(str(env('DJANGO_CORS_ORIGIN_WHITELIST')).strip('"').split())


ENVIRONMENT = env('DJANGO_ENV', 'develop')
SENTRY_IS_ENABLED = env('SENTRY_IS_ENABLED', 'false').lower() in true_values


Django settings for project.  Generated by 'django-admin startproject' using Django 2.1.1.  For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/  For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ # make gettext work in settings.py # https://github.com/DNX/django-simple-project/wiki/Translate-strings-in-settings.py # a convenient shortcut to import environment variables # this is a custom method to import required env variables # Build paths inside the project like this: os.path.join(BASE_DIR, ...) # SECURITY WARNING: don't run with debug turned on in production! # this env is set from the deploy script # SECURITY WARNING: keep the secret key used in production secret! # Application definition # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # Password validation # https://docs.djangoproject.com/en/2.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', #     }, # ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ # marked as optional in the doc but seems to be necessary for this setup # European # ISO (for native mobile datepickers) # US # some long formats # '14:30' # '14:30:59' # '14:30:59.000200' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ # email stuff # https://docs.python.org/3/library/logging.handlers.html # because of https://justinmontgomery.com/rotating-logs-with-multiple-workers-in-django # so that the auth migration files can be part of the project files, resolves stupid PSA bug / legacy thing # this is python social auth # there is no username field anymore # USER_FIELDS = ['email'] # AUTH_USER_MODEL = "usermgmt.User" # DRF # 'rest_framework_csv.renderers.CSVRenderer', # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. # 'api.auth.TokenAuthSupportQueryString', # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), # 'PAGE_SIZE': 10, # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', # 'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S.%fZ", # frontends wont work without CORS headers