"""
Django settings for sangue_django project.
"""

import os
import sys
from pathlib import Path

from dotenv import find_dotenv, load_dotenv

load_dotenv(find_dotenv())

def tristate_env_flag(name):
    env_flag = os.getenv(name)
    if env_flag:
        globals()[name] = True if env_flag.strip().lower() in (
    'true', '1') else False



# ADMINS =

ALLOWED_HOSTS = ['*']

ASGI_APPLICATION = "sangue_django.routing.application"

# AUTHENTICATION_BACKENDS =

# AUTHLIB_OAUTH_CLIENTS =

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

# AUTH_USER_MODEL =

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

# BOWER_COMPONENTS_ROOT =
# BOWER_INSTALLED_APPS =
# CACHES = {
#     "default": {
#         "BACKEND": "django_redis.cache.RedisCache",
#         "LOCATION": f"redis://{os.getenv('REDIS_HOST', 'Invalid redis host')}:{ os.getenv('REDIS_PORT', 'Invalid redis port')}/0",
#         "OPTIONS": {
#             "CLIENT_CLASS": "django_redis.client.DefaultClient",
#         }
#     }
# }
# CONTEXT =
# CORS_ORIGIN_ALLOW_ALL =
# CSP_FRAME_ANCESTORS =
tristate_env_flag('CSRF_COOKIE_SECURE')
MYHOSTNAME = os.getenv('MYHOSTNAME','http://imposta-MYHOSTNAME-nell-env.briq.it')
if not MYHOSTNAME.startswith('http'):
    if len(MYHOSTNAME.strip()) == 0:
        MYHOSTNAME = '127.0.0.1'
    MYHOSTNAME='http://'+MYHOSTNAME
CSRF_TRUSTED_ORIGINS = list({x for x in (os.getenv('CSRF_TRUSTED_ORIGINS','').split(',')+[MYHOSTNAME]) if x})
# DATABASE_ROUTERS =

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': os.getenv('DB_HOST'),
        'PORT': os.getenv('DB_PORT', "5432"),
        'CONN_MAX_AGE': 120,
        'TEST': {
            'NAME': os.getenv('DB_TEST_NAME')
        }
    }
}

DATA_UPLOAD_MAX_NUMBER_FIELDS = 10000

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG=True
DEBUG_TOOLBAR=False
tristate_env_flag('DEBUG')
if DEBUG:
    CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer"
        }
    }
    tristate_env_flag('DEBUG_TOOLBAR')
else:
    CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels_redis.core.RedisChannelLayer",
            "CONFIG": {
                "hosts": [(os.getenv("REDIS_HOST", "Invalid redis host"), os.getenv("REDIS_PORT", "Invalid redis port"))],
            },
        },
    }

DEBUG_TOOLBAR = True if os.getenv('DEBUG_TOOLBAR') in (
    'True', 'true', '1', 'TRUE') else False

DEFAULT_AUTO_FIELD='django.db.models.AutoField'
# DEPLOY_NAME =
# DOCS_DIR =
tristate_env_flag('ENABLE_MQTT')
if any(x in sys.argv for x in ['test', 'dumpdata', 'sqlshell', 'loaddata', 'sqlflush']):
    ENABLE_MQTT = False

FIXTURE_DIRS = (
    'sangue_app/fixtures/',
)

# IMPORT_EXPORT_USE_TRANSACTIONS

# Application definition
INSTALLED_APPS = [
    'sangue_app.apps.SangueAppConfig',
    'offerte_app.apps.OfferteAppConfig',
    'business_model_canvas_app.apps.BusinessModelCanvasAppConfig',
    'fattura_elettronica_app.apps.FatturaElettronicaAppConfig',
    'contatti_app.apps.ContattiAppConfig',
    'dati_geo_app.apps.DatiGeograficiAppConfig',
    'djaa_list_filter',
    'rest_framework',
    'admin_interface',
    'colorfield',
    # 'rest_framework.authtoken',
    'corsheaders',
    'drf_yasg',
    'import_export',
    'ordered_model',
    'polymorphic',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
    # 'django_q',
]
if DEBUG_TOOLBAR:
    INSTALLED_APPS.append('debug_toolbar')
if DEBUG:
    INSTALLED_APPS.append('django_extensions')

INTERNAL_IPS = [
    '127.0.0.1',
]

LANGUAGE_CODE = 'it-it'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'WARNING',
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
            'propagate': False,
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_SQL', 'INFO'),
            'propagate': False,
        },
    },
}

# LOGIN_REDIRECT_URL =
# LOGIN_URL =
# MAIN_SITE_URL =
# MANAGERS =

MEDIA_ROOT = os.getenv('MEDIA_ROOT')
if MEDIA_ROOT:
    MEDIA_ROOT=MEDIA_ROOT.replace("$(pwd)", os.path.realpath(os.path.dirname(BASE_DIR)))

MEDIA_URL = os.getenv('MEDIA_URL')

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',
]
if DEBUG_TOOLBAR:
    MIDDLEWARE = [
        'debug_toolbar.middleware.DebugToolbarMiddleware'] + MIDDLEWARE

if os.getenv('MQTT_HOST') and os.getenv('MQTT_PORT'):
    MQTT_ADDR = [os.getenv('MQTT_HOST'), int(os.getenv('MQTT_PORT'))]
else:
    # stesso default che usano i programmi mosquitto_pub etc
    MQTT_ADDR = ["localhost", 1883]

# PROJECT_ROOT =

Q_CLUSTER = {
    'name': 'sangue',
    'workers': 1,
    'recycle': 10,
    'timeout': 7200,
    'retry': 8000,
    'max_attempts': 2,
    'compress': True,
    'save_limit': 250,
    'queue_limit': 100,
    'cpu_affinity': 1,
    'label': 'Django Q',
    'django_redis': 'default',
    'redis': {
        'host': os.getenv("REDIS_HOST", "Invalid redis host"),
        'port': os.getenv("REDIS_PORT", "Invalid redis port"),
        'db': 0, },
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissions'
    ]
}

ROOT_URLCONF = 'sangue_django.urls'

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = (os.getenv('SECRET_KEY')
              if os.getenv('SECRET_KEY')
              else 'YCaAOqbBzWCYvNXfwbqntFvNhElemwclBzjWenTcpPYdYtcEOzAYfzkqnoqQYXKirtcDzRmwvpGCzuoRCkrMINUtWzEAonGKpcsZ')

# SECURE_HSTS_INCLUDE_SUBDOMAINS =
# SECURE_HSTS_PRELOAD =
# SECURE_HSTS_SECONDS =
# SECURE_PROXY_SSL_HEADER =
# SECURE_REFERRER_POLICY =
tristate_env_flag('SECURE_SSL_REDIRECT')
tristate_env_flag('SESSION_COOKIE_SECURE')

SILENCED_SYSTEM_CHECKS = ['security.W019'] # Per la modale di Django Admin interface

# SILKY_ANALYZE_QUERIES =
# SILKY_AUTHENTICATION =
# SILKY_AUTHORISATION =
# SILKY_INTERCEPT_PERCENT =
# SILKY_MAX_RECORDED_REQUESTS =
# SILKY_MAX_RESPONSE_BODY_SIZE =
# SILKY_PERMISSIONS =
# SITE_ID =
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

# STATICFILES_FINDERS =

STATIC_ROOT = '../django_static/'

STATIC_URL = '/static/'

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

# TEST_RUNNER =

TIME_ZONE = 'Europe/Rome'

USE_I18N = True

USE_L10N = True

USE_TZ = True

X_FRAME_OPTIONS = "SAMEORIGIN"