"""
Django settings for ogure project.

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

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

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

# 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.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY", "foo")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = int(os.environ.get("DEBUG", default=1))

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'backend.apps.BackendConfig',
    'corsheaders',
    'rest_framework',
    'django_filters',
    'drf_api_logger',
]

AUTH_USER_MODEL = "backend.CustomUser"
LOGIN_REDIRECT_URL = '/'

CSRF_COOKIE_SAMESITE = os.environ.get("DJANGO_CSRF_COOKIE_SAMESITE", 'Strict')
SESSION_COOKIE_SAMESITE = os.environ.get("DJANGO_SESSION_COOKIE_SAMESITE", 'Strict')
# CSRF_COOKIE_HTTPONLY = os.environ.get("DJANGO_CSRF_COOKIE_HTTPONLY", False)
CSRF_COOKIE_HTTPONLY = False
# False since we will grab it via universal-cookies
SESSION_COOKIE_HTTPONLY = os.environ.get("DJANGO_SESSION_COOKIE_HTTPONLY", False)
# Complete with all autorized domains
CSRF_TRUSTED_ORIGINS = ['*']
# PROD ONLY
# CSRF_COOKIE_SECURE = os.environ.get("DJANGO_# CSRF_COOKIE_SECURE", True)
# SESSION_COOKIE_SECURE = os.environ.get("DJANGO_# SESSION_COOKIE_SECURE", True)
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
# ajout manuel DRHAT
SESSION_COOKIE_AGE = 14400
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
CACHE_MIDDLEWARE_SECONDS = 600
#fin ajout
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
    'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework.authentication.SessionAuthentication'],
    'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAuthenticated'],
    'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

MIDDLEWARE = [
    'django.middleware.gzip.GZipMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'ogure.middleware.CustomCorsMiddleware',
    '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',
    'drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware',
    
]

ROOT_URLCONF = 'ogure.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 = 'ogure.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
if os.getenv('GAE_APPLICATION', None):
    # Running on production App Engine, so connect to Google Cloud SQL using
    # the unix socket at /cloudsql/<your-cloudsql-connection string>
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'HOST': '/cloudsql/ogure-ng:europe-west1:ogure-db',
            'USER': 'ogure',
            'PASSWORD': 'ogure',
            'NAME': 'ogure',
        }
    }
else:
    DATABASES = {
        'default': {
            "ENGINE":   os.environ.get("SQL_ENGINE",   "django.db.backends.postgresql"),
            "NAME":     os.environ.get("SQL_DATABASE", "Ogure-DB"),
            "USER":     os.environ.get("SQL_USER",     "postgres"),
            "PASSWORD": os.environ.get("SQL_PASSWORD", "S91g7xDDu9bYGA"),
            "HOST":     os.environ.get("SQL_HOST",     "localhost"),
            "PORT":     os.environ.get("SQL_PORT",     "5432"),
        }
    }

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

LANGUAGE_CODE = 'fr'

TIME_ZONE = 'Europe/Paris'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = "/staticfiles/"
STATIC_ROOT = [os.path.join(BASE_DIR, "staticfiles")]

STATICFILES_DIRS = [
    # Where Django should look for React's static files (css, js)
    #os.path.join(BASE_DIR, "frontend/dist"),
]

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

FORCE_SCRIPT_NAME = os.environ.get('DJANGO_FORCE_SCRIPT_NAME', '')

# Configuration des variables associ�es au log de requ�tes avec DRF-API-Logger
DRF_API_LOGGER_DATABASE = True  # Default to False
DRF_API_LOGGER_SLOW_API_ABOVE = 2000
# TODO : Sp�cifier ici l'ensemble des champs que l'on ne souhaite pas retrouver dans les logs de requ�te
DRF_API_LOGGER_EXCLUDE_KEYS = ['password', 'token', 'access', 'refresh', 'results']
# TODO : d�finir pr�cis�ment le format des logs qu'on veut visualiser et se lib�rer du format de donn�es de DRF-API-Logger
# FIXME : bug de suppression des logs dans l'admin

nb_max = os.getenv('MAX_CALCULS', None)
MAX_CALCULS = None if nb_max is None else int(nb_max)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '{asctime} {levelname} [{name}] {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': './debug.log',
            'formatter': 'standard',
        }
    },
    'loggers': {
        '': {
            'handlers': ['console', 'file'],
            'level': 'DEBUG',
        },
        'django': {
            'handlers': ['console', 'file'],
            #'level': os.getenv('DJANGO_LOG_LEVEL', 'WARNING'),
            'level': 'DEBUG',
            'propagate': False,
        },
        'django.db.backends': {
            'handlers': ['console'],
            #'level': os.getenv('DJANGO_LOG_LEVEL_DB', 'WARNING'),
            'level': 'DEBUG',
            'propagate': False,
        },
        'django.security.csrf': {
            'handlers': ['console'],
            #'level': os.getenv('DJANGO_LOG_LEVEL', 'WARNING'),
            'level': 'DEBUG',
            'propagate': False,
        },
        'backend': {
            'handlers': ['console', 'file'],
            #'level': os.getenv('APP_LOG_LEVEL', 'WARNING'),
            'level': 'DEBUG',
            'propagate': False,
        },
        'compute': {
            'handlers': ['console', 'file'],
            #'level': os.getenv('APP_LOG_LEVEL', 'WARNING'),
            'level': 'DEBUG',
            'propagate': False,
        },
        'ogure': {
            'handlers': ['console', 'file'],
            #'level': os.getenv('APP_LOG_LEVEL', 'WARNING'),
            'level': 'DEBUG',
            'propagate': False,
        },
    }
}
