"""
Django settings for lemma_rs_be project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from datetime import timedelta
from pathlib import Path
from typing import List
# from django_query_profiler.settings import *

import environ

root = environ.Path(__file__) - 2  # get root of the project
env = environ.Env()
env.read_env(env.str('ENV_PATH', '.env'))  # reading .env file

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

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/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.bool('DEBUG')

ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')

FORCE_SCRIPT_NAME = env('FORCE_SCRIPT_NAME')
STATIC_URL = env('STATIC_URL')
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

MEDIA_URL = env('MEDIA_URL')
MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles")

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'rest_framework',
    'corsheaders',
    'django_filters',
    'rs',
    # oauth
    'rest_framework.authtoken',  # only if you use token authentication
    'social_django',  # django social auth
    'rest_social_auth',  # this package
    # swagger
    'drf_spectacular',
    'rest_framework_api_key',
    'django_crontab',
    'django_apscheduler',
    # profiler
    # 'django_query_profiler'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    '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_query_profiler.client.middleware.QueryProfilerMiddleware',
]

CORS_ALLOWED_ORIGINS = env.list('CORS_ALLOWED_ORIGINS')

CORS_ALLOW_ALL_ORIGINS = env.bool('CORS_ALLOW_ALL_ORIGINS')

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Content-Disposition'
]

ROOT_URLCONF = 'lemma_rs_be.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',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

WSGI_APPLICATION = 'lemma_rs_be.wsgi.application'

# Profiler DB
# DATABASES = {
#     'default': {
#         'ENGINE': 'django_query_profiler.django.db.backends.postgresql',
#         'NAME': 'lemmars',
#         'USER': 'lemmars',
#         'PASSWORD': 'lemmars',
#         'HOST': '127.0.0.1',
#         'PORT': 5433
#     }
# }

DATABASES = {
    'default': env.db()
}

DEFAULT_RENDERER_CLASSES = (
    'rest_framework.renderers.JSONRenderer',
)

if DEBUG:
    DEFAULT_RENDERER_CLASSES = DEFAULT_RENDERER_CLASSES + (
        'rest_framework.renderers.BrowsableAPIRenderer',
    )

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

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    # swagger
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
    # filters
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
}

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'lemma_rs_be.muni_auth_be.Muni',
    'lemma_rs_be.mock_auth_be.Mock',
)

SOCIAL_AUTH_PIPELINE = (
    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    'social_core.pipeline.social_auth.associate_by_email',  # <--- enable this one
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
)

SOCIAL_AUTH_MUNI_KEY = env('SOCIAL_AUTH_MUNI_KEY')
SOCIAL_AUTH_MUNI_SECRET = env('SOCIAL_AUTH_MUNI_SECRET')
SOCIAL_AUTH_MUNI_USER_FIELDS = ['username', 'email', 'fullname']

SOCIAL_AUTH_MOCK_KEY = 'client-credentials-mock-client'
SOCIAL_AUTH_MOCK_SECRET = 'client-credentials-mock-client-secret'
SOCIAL_AUTH_MOCK_USER_FIELDS = ['username', 'email', 'fullname']

# REST_SOCIAL_OAUTH_REDIRECT_URI = env('REST_SOCIAL_OAUTH_REDIRECT_URI')
REST_SOCIAL_OAUTH_ABSOLUTE_REDIRECT_URI = env('REST_SOCIAL_OAUTH_ABSOLUTE_REDIRECT_URI')

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

LANGUAGE_CODE = 'en-EN'

TIME_ZONE = 'Europe/Prague'

USE_I18N = True

USE_L10N = True

USE_TZ = True
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

AUTH_USER_MODEL = 'rs.User'

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=3),
}

# DJANGO_QUERY_PROFILER_REDIS_HOST = 'localhost'
# DJANGO_QUERY_PROFILER_REDIS_PORT = 6379
# DJANGO_QUERY_PROFILER_REDIS_DB = 'test'


EMAIL_BACKEND = env('EMAIL_BACKEND')
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'rs.lemma.fi.muni@gmail.com'
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')
DEFAULT_FROM_EMAIL = 'rs.lemma.fi.muni@gmail.com'

