"""
Django settings for bookstore_project project.

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

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

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

import os
import socket

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

# ENVIRONMENT = os.environ.get('development', default='development') # this line is for production,set the default to production since it's always good to default to productin settings,otherwise you risk deploying a project that has security vulnerabilites

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_weon)*budt_$mly(qpevni(04t#*5kc0t(0kzdob112@$+i+!'


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# when debug is false it must be set explicitly and include values,the two ways we access it locally which are 127.0.0.1 or localhost
# ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1']

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    # if you use allauth then you have to add django.contrib.sites as well as add allauth and allauth.account, firstly you install this package
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'crispy_forms',
    'allauth',
    'allauth.account',
    'debug_toolbar',  # 3rd party toolbar for debuging,for that reason you have to install this 3rd party tool
    'users.apps.UsersConfig',
    'pages.apps.PagesConfig',
    'books.apps.BooksConfig',
    'orders.apps.OrdersConfig',
]

MIDDLEWARE = [
    'django.middleware.cache.UpdateCacheMiddleware',  # using django build in memcached for caching(caching is memory storing expensive calculation,once executed it doesn't need to be run again)
    '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',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',  # this django cache use for per-site caching(caches entire site)
]

ROOT_URLCONF = 'bookstore_project.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',
            ],
        },
    },
]

WSGI_APPLICATION = 'bookstore_project.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/2.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/2.0/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/2.0/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] # the list of static files dirs,here it can be multiple dirs

# django-crispy-forms
CRISPY_TEMPLATE_PACK = 'bootstrap4'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATIC_ROOT is the location of the static files for production so it must be set to a different name typically staticfiles,in deploy the collectstatic
# command will automatically compile all available static files throughout the entire project into a single directory.this is faster then local development

# this one tells django how to look for static file directories,although it is implicitly set,define here is optional
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",  # the FileSystemFinder looks within the STATICFILES_DIRS settings,which we set to static for any static files
    "django.contrib.staticfiles.finders.AppDirectoriesFinder", # the AppDirectoriesFinder looks for any directories named static located within an app
]

#This setting is read top-to-bottom meaning if a file called static/img.jpg is first found by FileSystemFinder it will be in place of an img.jpg file located within, say, the pages app at pages/static/img.jpg.

AUTH_USER_MODEL = 'users.CustomUser' # define custom user model before the migrate command
LOGIN_REDIRECT_URL = 'home' # you have to define the url name in explicitly where redirect after login,otherwise the django build in redirect to accounts/profile url
#LOGOUT_REDIRECT_URL = 'home' # after logout,the redirect url name

ACCOUNT_LOGOUT_REDIRECT = 'home' # django allauth overrides the build in LOGOUT_REDIRECT_URL,here these two logout redirect are same,but other projects we don't want to redirect home after logout


SITE_ID = 1 # we only have one site in our project then we'll set the SITE_ID =1,if we added a second site it would have an ID of 2

# for password reseting in command console using 3rd party allauth
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # by default Django will look for a configured SMTP server to send emails,here using console instead of smtp

'''
# if i use sendgrid in place of command line then you have to set this
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # update the email backend using smtp in place of command console
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'sendgrid_username' # set sendgrid_username
EMAIL_HOST_PASSWORD = 'sendgrid_password' # set sedgrid_password
EMAIL_PORT = 587    # Email_PORT and EMAIL_USE_TLS set based on the instructions from your email provider as environment variables
EMAIL_USE_TLS = True
'''

AUTHENTICATION_BACKENDS = (
    # needed to login by username in Django admin,regardless of 'allauth'
    'django.contrib.auth.backends.ModelBackend', # which is used when Django attempts to authenticate a user
    # 'allauth' specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend', # here we specify specific authentication options which allow us to switch over to using login via email
)
# so don't show the 'remember me' icon in login page,it always true in here
ACCOUNT_SESSION_REMEMBER = True  # The default None asks the user if they want their session to be remembered so they
# don't have to log in again.It can also be set to False to not remember or True to always remember

ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False # an optional customization of django-allauth is ask for a password once,
# since we'll configure password change and reset options so don't need to use password twice

# here we config email for login/signup in place of using username(in django allauth)
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True  # using email for sign up in place of username
ACCOUNT_UNIQUE_EMAIL = True
# when we use email for sign up then automatically set the username in admin is before the @ of email,if the model has
# still has username field
DEFAULT_FROM_EMAIL = 'admin@djangobookstore.com'  # for signup process here using command console and sent a email from
# 'admin@djangobookstore.com' in place of webmaster@localhost(which one is default)

# by default MEDIA_URL and MEDIA_ROOT are empty and not displayed so we need to configure them
MEDIA_URL = '/media/'  # it is the URL we can use in our templates for the files
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # it is the abs file system path to the directory for user uploaded files
# we add this media_url and media_root then we add these in urlpatterns in bookstore_projects/urls file


STRIPE_PUBLISHABLE_KEY = 'pk_test_CdSp3QAqNnsH7LLZATjfy1Hj00rUbvBD8n' # the publishable key will be embedded in the Javascript on our webpage,it is public and visible,(set the key's from website)
STRIPE_SECRET_KEY = 'sk_test_0gI88gocjjPfBUqGfEbeXOEt00ZPVTa7YL'  # the secret key is stored on the server and is for private use only


# django-debug-toolbar(you have to import socket),it is using for improving performance,generally optimizing db querires,caching,indexes,compressing front-end assets like images,JavaScript,CSS
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS = '127.0.0.1'  # if we were not in Docker this could be '127.0.0.1',for docker[ip[:-1] + "1" for ip in ips]

# if we don't use the django build in memcache,then the dubg_toolbar shows the cache,but it's not working,if we activate the memcache then we can see in debug toolbar is the time is very less and cache is called
# here using django build in memcache,set this value on cache,caching is use for speed up on large site,adding two lines on middleware
CACHE_MIDDLEWARE_ALIAS = 'default' # default number of seconds (600) to cache a page,after the period is up,the cache expires and become empty
CACHE_MIDDLEWARE_SECONDS = 604800 # a good default when starting out is 604800 seconds or 1 week(60*60*24*7) for a site with content that doesn't change very often,but if your cache is filling up rapidly or running a site where the content changes on a frequent basis,shortening this settings time is a good step
CACHE_MIDDLEWARE_KEY_PREFIX = ''
# in a large project we have to do caching,the extra complexity of Mamcache is, must be run as a separate instance,on herokeu there are a free tier availbable Memcachier


# csrf protection is that type of protection where it prevents using secret key on csrf_token(html file) and csrf_middleware,malicious actor give a link for accessing login and passsword to give a link 
# it use the X-XSS-Protection Header to help the guard against XSS attacks,XSS attacks means in a page create a code in javascript from malicious user, to prevent this django automatically escape specific characters including brackets,single quots,double qoutes etc
if ENVIRONMENT == 'production' # in local env there are no XSS attack
    SECURE_BROWSER_XSS_FILTER = True  # using XSS filter for removing XSS attack
    X_FRAME_OPTIONS = 'DENY' # default is 'SAMEORIGIN', here don't using X_FRAME_OPTIONS,means there are no use of iframe which is like a picture of amazon product in malicisou site,if you want to see more products then this products automatically purchased
    SECURE_SSL_REDIRECT = True  # here we can force all non-HTTPS traffic to be redirected to HTTPS,HTTP have encryption,and 's' in HTTPS refers to its encrypted nature first due to SSL and these days its successor TLS
    SECURE_HSTS_SECONDS = 3600 # HSTS is a security policy that web browsers should only interact via HTTPS by adding a STS,add a small value of time for testing,later extending it to one year,done in SECURE_HSTS_SECONDS config which is implicitly set to 0
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True # we don't have any subdomains in our project so it make sense to force any subdomains to also exclusively use SSL via SECURE_HSTS_INCLUDE_SUBDOMAINS setting
    SECURE_HSTS_PRELOAD = True
    SECURE_CONTENT_TYPE_NOSNIFF = True # with HTTPS enabled,malicious actor can't sniff the incoming and outgoing traffic for data like authentication credentials or API keys
    SESSION_COOKIE_SECURE = True # HTTP cookie is used to store information on a client's computer such as authentication credentials,django uses sessions and cookies for this,but cookies it should be forced over HTTPS  as well as via SESSION_COOKIE_SECURE config,we must set it true in production
    CSRF_COOKIE_SECURE = True # the cookie secure in csrf protection

