"""
Django settings for samples project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os
from decouple import config

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

# Used for a default title
APP_NAME = 'Digi Louvre'

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

# SECURITY WARNING: keep the secret key used in production secret!

SECRET_KEY = config('SECRET_KEY')


# SECURITY WARNING: don't run with debug turned on in production!

DEBUG = config('DEBUG', cast=bool)

ALLOWED_HOSTS = ['*']

# Application definition

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

    # Extensions - installed with pip3 / requirements.txt
    'django_extensions',
    'crispy_forms',
    'rest_framework',
    # 'social_django',
    'home.apps.HomeConfig',

    # Sample Applications - don't copy
    'dl.apps.DlConfig',

    'imagekit',
    'django_cleanup.apps.CleanupConfig',
    'django_countries',
    'paypal.standard.ipn',
    'paypal.standard',
    'django_filters',
    'axes',
    # 'django-simple-captcha',
    # 'captcha',
]

PAYPAL_TEST = False

PAYPAL_RECEIVER_EMAIL = config('PAYPAL_RECEIVER_EMAIL')
ADMIN_EMAIL = config('ADMIN_EMAIL')

# When we get to crispy forms :)
CRISPY_TEMPLATE_PACK = 'bootstrap3'  # Add

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    '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',
    'social_django.middleware.SocialAuthExceptionMiddleware',   # Add
    'csp.middleware.CSPMiddleware',
    'axes.middleware.AxesMiddleware',
]

ROOT_URLCONF = 'mysite.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',
                'home.context_processors.settings',      # Add
                'social_django.context_processors.backends',  # Add
                'social_django.context_processors.login_redirect', # Add
                'csp.context_processors.nonce',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


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

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': config('DB_HOST'),
        'OPTIONS': {
            # 'init_command': 'SET innodb_strict_mode=1',
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1",
        },
    }
}

# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT', cast=int)
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')
EMAIL_USE_TLS = True

# Password validation
# https://docs.djangoproject.com/en/3.0/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/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

# TIME_ZONE = 'UTC'
TIME_ZONE = 'America/New_York'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# STRIPE_KEY = 'sk_test_51IBNYyI9DIx7WcqFZNY6FZAhWntn6bOizYO8bCYTMBGDIs4srO4Oz7ZC141M6qaSQIxanGtOYBQWAdOJ9DTb4gyB00xejWfAQD'
STRIPE_KEY = config('STRIPE_PRIVATE_KEY')

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

STATIC_URL = '/static/'
STATIC_ROOT = '/home/digilouvre/django_projects/static'

MEDIA_URL = '/media/'
# for production url could be: /home/mysite/media/
MEDIA_ROOT = 'media/'
# MEDIA_ROOT = '/home/digilouvre/django_projects/media'




# TEMPLATE_CONTEXT_PROCESSORS

# Add the settings below

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

# Configure the social login
try:
    from . import github_settings
    SOCIAL_AUTH_GITHUB_KEY = github_settings.SOCIAL_AUTH_GITHUB_KEY
    SOCIAL_AUTH_GITHUB_SECRET = github_settings.SOCIAL_AUTH_GITHUB_SECRET
except:
    print('When you want to use social login, please see mysite/github_settings-dist.py')

# https://python-social-auth.readthedocs.io/en/latest/configuration/django.html#authentication-backends
# https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html
AUTHENTICATION_BACKENDS = (
    'axes.backends.AxesBackend',
    'social_core.backends.github.GithubOAuth2',
    # 'social_core.backends.twitter.TwitterOAuth',
    # 'social_core.backends.facebook.FacebookOAuth2',

    'django.contrib.auth.backends.ModelBackend',
)

LOGOUT_REDIRECT_URL = '/'
LOGIN_REDIRECT_URL = '/'

# Don't set default LOGIN_URL - let django.contrib.auth set it when it is loaded
# LOGIN_URL = '/accounts/login'

# https://coderwall.com/p/uzhyca/quickly-setup-sql-query-logging-django
# https://stackoverflow.com/questions/12027545/determine-if-django-is-running-under-the-development-server


# django-csp headers:

CSP_STYLE_SRC = (
    "'self'",
    "cdnjs.cloudflare.com",
    "use.fontawesome.com",
    "fonts.googleapis.com",
    "'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='",
    "'sha256-OTeu7NEHDo6qutIWo0F2TmYrDhsKWCzrUgGoxxHGJ8o='",
    "'sha256-xW6Sm5DSIzsGOz33kiGmYRCd4xdcnrYvxdyr96EWC/o='",
    "'sha256-aP33zotMllC2+85EQlL40wB2p6J/K2ouyIytJ5DQeYA='",
    "'sha256-pHt0kRn1eEo23ySyDqVDAbezsvnwttbDTDTlo3/I330='",
    )

CSP_SCRIPT_SRC = ("'self'",
    "maxcdn.bootstrapcdn.com",
    "static.cloudflareinsights.com",
    "www.google-analytics.com",
    "ssl.google-analytics.com",
    "cdn.ampproject.org",
    "www.googletagservices.com",
     "js.stripe.com",
     )

CSP_IMG_SRC = ("'self'",
    "www.google-analytics.com",
    "raw.githubusercontent.com",
    "googleads.g.doubleclick.net",
    "www.paypal.com",
    'www.paypalobjects.com',
    "data:")

CSP_FONT_SRC = ("'self'",
    "cdnjs.cloudflare.com",
    "use.fontawesome.com",
    "fonts.gstatic.com",
    "data:",
    )

CSP_CONNECT_SRC = ("'self'",
    "www.google-analytics.com",
    "api.stripe.com")
CSP_OBJECT_SRC = ("'none'", )
CSP_BASE_URI = ("'self'", )
CSP_FRAME_SRC = ("js.stripe.com", "hooks.stripe.com")
CSP_FRAME_ANCESTORS = ("'self'", "js.stripe.com", "hooks.stripe.com" )
CSP_FORM_ACTION = (
    "'self'",
    'ipnpb.paypal.com',
    )
CSP_INCLUDE_NONCE_IN = ('script-src', 'style-src' )
CSP_MANIFEST_SRC = ("'self'", )
CSP_WORKER_SRC = ("'self'", )
CSP_MEDIA_SRC = ("'self'", )
CSP_CONNECT_SRC = ("'self'",)
CSP_DEFAULT_SRC = ("'none'",)

# Security settings for production:

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True

SECURE_HSTS_SECONDS = 15768000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

'''  # Leave off for now
import sys
if (len(sys.argv) >= 2 and sys.argv[1] == 'runserver'):
    print('Running locally')
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
            }
        },
        'loggers': {
            'django.db.backends': {
                'handlers': ['console'],
                'level': 'DEBUG',
            },
        }
    }
'''
