"""
Django settings for layman_erp project.

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

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

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

import django_heroku

# ENV is defined in api.settings
from api.settings import *

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

DEBUG = ENV('DEBUG', cast=bool, default=True)

IS_PROD = ENV('IS_PRODUCTION', default=(ENVIRONMENT == 'production'), cast=bool)
IS_STAGING = ENV('IS_STAGING', default=(ENVIRONMENT == 'staging'), cast=bool)

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ENV('SECRET_KEY', default='^f*zkpi9pfi83qwa!$e!g@(3!@#r!&35q&l6^uha3msh_7f_@y')

DEFAULT_FRONTEND_APP_DOMAIN = 'localhost:3000'
DEFAULT_APP_DOMAIN = 'localhost:8080'
ALLOWED_HOSTS = []

# Domain/Routing Management
CORS_ORIGIN_ALLOW_ALL = ENV('CORS_ORIGIN_ALLOW_ALL', default=True, cast=bool)
FRONTEND_APP_DOMAIN = ENV('FRONTEND_APP_URL', default=DEFAULT_FRONTEND_APP_DOMAIN)
ALLOWED_DOMAIN = ENV('ALLOWED_DOMAIN', default=DEFAULT_APP_DOMAIN)
APP_DOMAIN = ENV('APP_DOMAIN', default=DEFAULT_APP_DOMAIN)
ALLOWED_HOSTS += [ALLOWED_DOMAIN]
ALLOWED_HOSTS += [APP_DOMAIN]
SHORT_DOMAIN = sorted(ALLOWED_HOSTS)[0]

# Reference: https://docs.scoutapm.com/#django
SCOUT_NAME = "LaymanERP API"


# Application definition

INSTALLED_APPS = [
    'scout_apm.django',
    'layman_erp.admin.AdminConfig',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',

    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',

    'django.contrib.postgres',

    # Third-Party Apps
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'drf_yasg',
    'django_filters',

    # Local Apps
    'core.apps.CoreConfig',
    'api.apps.ApiConfig',

    # Useful Tools
    'django_extensions'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
    'crum.CurrentRequestUserMiddleware'
]

ROOT_URLCONF = 'layman_erp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'core/templates'),
            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',
                'layman_erp.context_processors.api_keys',
                'layman_erp.context_processors.environment_variables',
            ],
        },
    },
]

WSGI_APPLICATION = 'layman_erp.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': ENV('DATABASE_NAME', default='layman'),
        'USER': ENV('DATABASE_USER', default='layman'),
        'PASSWORD': ENV('DATABASE_PASSWORD', default='<PASSWORD>'),
        'HOST': ENV('DATABASE_HOST', default='127.0.0.1')
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 10,
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
    {
        'NAME': 'layman_erp.validators.PasswordCombinationValidator',
    }
]


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'


class DummyInternalIPs:
    """Dummy class for whitelisting all IPs as internal IP while doing local dev

    In local dev environment if you want to whitelist all IPs as internal you can use
    this class within your local settings like: `INTERNAL_IPS = DummyInternalIPs()`
    """

    def __init__(self):
        """Placeholder constructor which does nothing"""

    def __contains__(self, address):
        """Blindly white list the test for local dev"""
        return True


# Activate Django-Heroku.
django_heroku.settings(locals())


# For local configurations create a directory named env and a file named local.py in it
try:
    from .env.local import *  # pylint: disable=wildcard-import
except ImportError:
    pass
