"""
Django settings for growup project.

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

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/
"""

from pathlib import Path

from environs import Env

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

env = Env()
env.read_env(recurse=False, path=Path.joinpath(BASE_DIR, '.env'), override=True)

# Web_Engage
WEBENGAGE_ENABLED = env.bool('WEBENGAGE_ENABLED', False)
with env.prefixed('WEBENGAGE_') as e:
    WEBENGAGE_LICENSE_CODE = e("LICENSE_CODE", "")
    WEBENGAGE_API_KEY = f'Bearer {e("API_KEY", "")}'

APP_BASE_URL = env.str('APP_BASE_URL', '')
RAPID_BASE_URL = env.str('RAPID_BASE_URL', '')
APP_SHORT_URL = env.str('APP_SHORT_URL', '')

# 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 = ['*']

CORS_ALLOW_ALL_ORIGINS = True
CORS_EXPOSE_HEADERS = ['X-Link']

# Application definition

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

    'api.apps.ApiConfig',
    'shortener.apps.ShortenerConfig',
]

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 = 'growup.urls'

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

WSGI_APPLICATION = 'growup.wsgi.application'

# DRF
_DEFAULT_TIME_RELATED_FORMAT = '%s'
REST_FRAMEWORK = dict(
    EXCEPTION_HANDLER='rest_framework.views.exception_handler',
    DEFAULT_FILTER_BACKENDS=('django_filters.rest_framework.DjangoFilterBackend',),
    DEFAULT_PAGINATION_CLASS='utils.views.CustomPagination',
    # DEFAULT_PERMISSION_CLASSES=('rest_framework.permissions.IsAuthenticated',),
    DEFAULT_AUTHENTICATION_CLASSES=('rest_framework_simplejwt.authentication.JWTAuthentication',),
    UNAUTHENTICATED_USER=None,
    DEFAULT_RENDERER_CLASSES=('rest_framework.renderers.JSONRenderer',),
    # DATE_FORMAT=_DEFAULT_TIME_RELATED_FORMAT,
    # DATE_INPUT_FORMATS=[_DEFAULT_TIME_RELATED_FORMAT],
    # DATETIME_FORMAT=_DEFAULT_TIME_RELATED_FORMAT,
    # DATETIME_INPUT_FORMATS=[_DEFAULT_TIME_RELATED_FORMAT],
    # TIME_FORMAT=_DEFAULT_TIME_RELATED_FORMAT,
    # TIME_INPUT_FORMATS=[_DEFAULT_TIME_RELATED_FORMAT],
)

DRF_ENABLED = env.bool('DRF_ENABLED', False)
if DRF_ENABLED:
    INSTALLED_APPS.append('drf_yasg')  # noqa
    SWAGGER_SETTINGS = dict(
        # DEFAULT_AUTO_SCHEMA_CLASS='utils.schema.CustomSwaggerAutoSchema',
        # SECURITY_DEFINITIONS=dict(Bearer={'type': 'apiKey', 'name': 'Authorization', 'in': 'header'}),
        # JSON_EDITOR=True,
        # VALIDATOR_URL=None,
        # SHOW_REQUEST_HEADERS=False,
        # APIS_SORTER='alpha',
        # DEEP_LINKING=True,
        # USE_SESSION_AUTH=True,
        # REFETCH_SCHEMA_WITH_AUTH=True,
        # PERSIST_AUTH=False,
        # DOC_EXPANSION='none',
        DEFAULT_PAGINATOR_INSPECTORS=('utils.schema.CustomPaginationSchema',
                                      'drf_yasg.inspectors.CoreAPICompatInspector'),
        # DEFAULT_FIELD_INSPECTORS=(
        #     'utils.drf_inspectors.RangeFieldInspector',
        #     'utils.drf_inspectors.ChoiceFieldInspector',
        #     'drf_yasg.inspectors.CamelCaseJSONFilter',
        #     'drf_yasg.inspectors.RecursiveFieldInspector',
        #     'drf_yasg.inspectors.ReferencingSerializerInspector',
        #     'drf_yasg.inspectors.FileFieldInspector',
        #     'drf_yasg.inspectors.DictFieldInspector',
        #     'drf_yasg.inspectors.HiddenFieldInspector',
        #     'drf_yasg.inspectors.RelatedFieldInspector',
        #     'drf_yasg.inspectors.SerializerMethodFieldInspector',
        #     'drf_yasg.inspectors.SimpleFieldInspector',
        #     'drf_yasg.inspectors.StringDefaultFieldInspector',
        # )
    )
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

with env.prefixed('DB_') as e:
    DATABASES = {
        'default': dict(
            ENGINE='django.db.backends.postgresql_psycopg2',
            NAME=e('NAME'),
            USER=e('USER'),
            PASSWORD=e('PASS'),
            HOST=e('HOST'),
            PORT=e('PORT')
        )
    }

# 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',
    },
]

# JWT Config
# SIMPLE_JWT = {
#     # It will work instead of the default serializer(TokenObtainPairSerializer).
#     "TOKEN_OBTAIN_SERIALIZER": "api.serializers.MyTokenObtainPairSerializer",
#     # ...
# }

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = Path.joinpath(BASE_DIR, 'media')
STATIC_ROOT = Path.joinpath(BASE_DIR, 'static')
