"""
Django settings for config project.

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

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

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

from pathlib import Path
import os
import environ

env = environ.Env(
	DEBUG=(bool, False)
)

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

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

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

ALLOWED_HOSTS = env('ALLOWED_HOSTS').split(',')

CORS_ALLOWED_ORIGINS = [ 'https://' + url for url in env('ALLOWED_HOSTS').split(',')]
CORS_ALLOWED_ORIGINS += [ 'http://' + url for url in env('ALLOWED_HOSTS').split(',')]

CSRF_TRUSTED_ORIGINS = CORS_ALLOWED_ORIGINS


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # third-party
    'channels', # as high as possible (channels overloads 'runserver', may conflict with e.g. whitenoise)
    'rest_framework',
    'corsheaders',
    'rest_framework_simplejwt',
    'drf_yasg',
    'storages',
    'django_extensions',
    'django_tex',
    'colorfield',
    'django_celery_results',

    # local
    'websocket',
    'accounts',
    'photo_log',
    'api',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates/')],
        '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',
            ],
        },
    },
    {
        'NAME': 'tex',
        'BACKEND': 'django_tex.engine.TeXEngine',
        'APP_DIRS': True,
        'DIRS': [os.path.join(BASE_DIR, 'templates/')],
    },
]

LATEX_INTERPRETER = 'xelatex'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

WSGI_APPLICATION = 'config.wsgi.application'
ASGI_APPLICATION = 'config.asgi.application'


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

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


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

AUTH_USER_MODEL = 'accounts.CustomUser'


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'CET'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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


# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


# joins list of strings while making sure there is a slash between each element
# e.g. joinWithSlash(['a', 'b', 'c']) -> 'a/b/c/'
def joinWithSlash(stringList):
	return ''.join([string if string.endswith('/') else string+'/' for string in stringList])


MINIO = True
if MINIO:
    # MinIO S3 Object-Storage
    DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
    #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'

    AWS_ACCESS_KEY_ID = env('S3_ACCESS_ID')
    AWS_SECRET_ACCESS_KEY = env('S3_ACCESS_SECRET')
    AWS_STORAGE_BUCKET_NAME = env('S3_BUCKET_NAME')
    AWS_S3_ENDPOINT_URL = env('S3_ENDPOINT_URL')
    AWS_DEFAULT_ACL = 'public'
    
    MEDIA_URL = joinWithSlash([env('S3_ENDPOINT_URL'), env('S3_BUCKET_NAME')])
    #STATIC_URL = 'https://minio.riezel.com/zierle-training/'

    AWS_S3_OBJECT_PARAMETERS = {
            'CacheControl': 'public, max-age=86400',
    }
else:
    MEDIA_URL = 'media/'
    MEDIA_ROOT = BASE_DIR / 'media'

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
#STATICFILES_DIRS = [os.path.join(BASE_DIR, "static/")]



# Celery
# See https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html
CELERY_CACHE_BACKEND = 'default'

CELERY_WORK_DIR = env('TASK_WORKER_DIR')

CELERY_BROKER_URL = env.cache_url('MSG_BROKER_URL')['LOCATION']
CELERY_RESULT_BACKEND = env.cache_url('MSG_BROKER_URL')['LOCATION']
CELERY_EVENT_QUEUE_PREFIX = env('MSG_BROKER_PREFIX')

CELERY_TIMEZONE = 'CET'

CELERY_TASK_DEFAULT_QUEUE = env('TASK_DEFAULT_QUEUE')
CELERY_BROKER_TRANSPORT_OPTIONS = {
    'visibility_timeout': 300,
}


# Redis Cache
# See https://docs.djangoproject.com/en/4.1/topics/cache/

CACHES = {
    'default': {
        "BACKEND": env.cache_url('MSG_BROKER_URL')['BACKEND'],
        "LOCATION": env.cache_url('MSG_BROKER_URL')['LOCATION'],
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        },
        "KEY_PREFIX": env('CACHE_KEY_PREFIX'),
    }
}


# Django Channels - Channel Layers Backend
# See https://channels.readthedocs.io/en/stable/topics/channel_layers.html
# See https://pypi.org/project/channels-redis/ for settings configuration

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [(env('WS_BACKEND_HOST'), env('WS_BACKEND_PORT'))],
            "prefix": env('WS_BACKEND_PREFIX'),
            "group_expiry": 7200,
        },
    },
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 9999,
}

from datetime import timedelta

SIMPLE_JWT = {
    'REFRESH_TOKEN_LIFETIME': timedelta(days=30),
}
