"""
Django settings for webserver project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import logging
import environ
import os
from pathlib import Path
from context.context_creator import setup_logging
from database.connector import init_db

env = environ.Env(
    # set casting, default value
    # DEBUG=(bool, False)
)
BASE_DIR = Path(__file__).resolve().parent.parent.parent
SOURCE_DIR = Path(__file__).resolve().parent.parent
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

APP_ENV = env('APP_ENV')
if APP_ENV == "production":
    DEBUG = False
    setup_logging(logging.ERROR)
else:
    DEBUG = True
    setup_logging(logging.DEBUG)

DOMAIN_NAME = os.environ['DOMAIN_NAME']
HTTPS_DOMAIN_NAME = "https://" + DOMAIN_NAME
SERVER_NAME = DOMAIN_NAME
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']


# Security Settings
ALLOWED_HOSTS = [DOMAIN_NAME,
                 "firmwaredroid-backend:5000",
                 HTTPS_DOMAIN_NAME,
                 "localhost",
                 "fmd.localhost",
                 "fmd.localhost:4443"]
CSRF_TRUSTED_ORIGINS = [HTTPS_DOMAIN_NAME]
CORS_ALLOWED_ORIGINS = [HTTPS_DOMAIN_NAME,
                        "https://fmd.localhost",
                        "https://localhost",
                        "https://fmd.localhost:4443",
                        "https://127.0.0.1"]
CORS_ORIGIN_WHITELIST = [DOMAIN_NAME,
                         "fmd.localhost",
                         "localhost",
                         "127.0.0.1",
                         "https://fmd.localhost",
                         "https://fmd.localhost:4443",
                         "https://localhost",
                         "https://127.0.0.1"]
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'origin',
    'keep-alive',
    'user-agent',
    'cache-control',
    'content-type',
    'content-transfer-encoding',
    'custom-header-1',
    'x-accept-content-transfer-encoding',
    'x-accept-response-streaming',
    'x-user-agent',
    'x-grpc-web',
    'grpc-timeout',
    'authorization'
]
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]

CORS_ADDITIONAL_HOST_LIST = os.environ['CORS_ADDITIONAL_HOST'].split(";")
logging.info("CORS_ADDITIONAL_HOST_LIST: " + str(CORS_ADDITIONAL_HOST_LIST))
for cors_host in CORS_ADDITIONAL_HOST_LIST:
    if not cors_host.startswith("https://"):
        cors_host = "https://" + cors_host
    CORS_ORIGIN_WHITELIST.append(cors_host)
    CORS_ALLOWED_ORIGINS.append(cors_host)

CORS_ALLOW_CREDENTIALS = True

GRAPHQL_JWT = {
    'JWT_COOKIE_NAME': 'jwt-session',
    'JWT_COOKIE_SECURE': False,
    'JWT_COOKIE_SAMESITE': "Lax"
}

# Folder Config
MAIN_FOLDER = "../file_store/"
FILE_STORAGE_FOLDER = ""
FIRMWARE_FOLDER_IMPORT = ""
FIRMWARE_FOLDER_IMPORT_FAILED = ""
FIRMWARE_FOLDER_STORE = ""
FIRMWARE_FOLDER_APP_EXTRACT = ""
FIRMWARE_FOLDER_FILE_EXTRACT = ""
FIRMWARE_FOLDER_CACHE = ""
LIBS_FOLDER = ""

# Database Config
DB_REPLICA_SET = os.environ['MONGODB_REPLICA_SET']
DB_HOST = os.environ['MONGODB_HOSTNAME']
DB_HOST_PORT = int(os.environ['MONGODB_PORT'])
DB_NAME = os.environ['MONGODB_DATABASE_NAME']
DB_AUTH_SRC = os.environ['MONGODB_AUTH_SRC']
DB_URI = 'mongodb://' + os.environ['MONGODB_USERNAME'] \
         + ':' + os.environ['MONGODB_PASSWORD'] \
         + '@' + os.environ['MONGODB_HOSTNAME'] \
         + ':' + str(DB_HOST_PORT) \
         + '/' + os.environ['MONGODB_DATABASE_NAME'] \
         + '?authSource=' + DB_AUTH_SRC

# Database - Settings side-loaded by mongo-engine
MONGO_DATABASES = {
    "default": {
        "db": DB_NAME,
        "name": DB_NAME,
        "host": DB_HOST,
        "password": os.environ['MONGODB_PASSWORD'],
        "username": os.environ['MONGODB_USERNAME'],
        "tz_aware": True,
        "port": DB_HOST_PORT,
        "authSource": DB_AUTH_SRC,
        "authMechanism": "SCRAM-SHA-256"
    },
}

db = init_db(MONGO_DATABASES["default"])

# DJANGO REST API Config
API_TITLE = os.environ['API_TITLE']
API_VERSION = os.environ['API_VERSION']
API_DESCRIPTION = os.environ['API_DESCRIPTION']
API_PREFIX = os.environ['API_PREFIX']
API_DOC_FOLDER = os.environ['API_DOC_FOLDER']

# FMD - Firmware Mass Import Config
MASS_IMPORT_NUMBER_OF_THREADS = os.environ['MASS_IMPORT_NUMBER_OF_THREADS']

# Log configuration
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "level": "DEBUG",
    "formatters": {
        "verbose": {
            "format": "{asctime} {name} {levelname} {module} {process:d} {thread:d} {funcName} {message}",
            "style": "{",
        },
        "simple": {
            "format": "{asctime} {levelname} {funcName} {message}",
            "style": "{",
        },
    },
}

# Application definition
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    'corsheaders',
    "graphene_django",
    "setup",
    "django_rq",
    'rest_framework',
    "file_download.apps"
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "webserver.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",
            ],
        },
    },
]

WSGI_APPLICATION = "webserver.wsgi.application"

# SQL-Lite Test Database of DJANGO - Keep it for the user accounts
DJANGO_SUPERUSER_PASSWORD = os.environ["DJANGO_SUPERUSER_PASSWORD"]
DJANGO_SUPERUSER_USERNAME = os.environ["DJANGO_SUPERUSER_USERNAME"]
DJANGO_SUPERUSER_EMAIL = os.environ["DJANGO_SUPERUSER_EMAIL"]
DJANGO_SQLITE_DATABASE_PATH = os.environ['DJANGO_SQLITE_DATABASE_PATH']
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": DJANGO_SQLITE_DATABASE_PATH + "db.sqlite3",
    }
}

# Internationalization - see https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images) - see https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = "/django_static/"
STATIC_ROOT = os.path.join(SOURCE_DIR, "static/")
FORCE_SCRIPT_NAME = '/'
USE_X_FORWARDED_HOST = True
LOGIN_URL = '/admin/login/'
LOGIN_REDIRECT_URL = '/admin/'
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Default primary key field type - see https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# Graphql Graphene configuration
GRAPHENE = {
    "SCHEMA": "api.v2.schema.FirmwareDroidRootSchema.schema",
    "MIDDLEWARE": [
        "graphql_jwt.middleware.JSONWebTokenMiddleware",
        'graphene_django.debug.DjangoDebugMiddleware',
    ],
}

# Authentication
# Password validation https://docs.djangoproject.com/en/4.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",
    },
]
AUTHENTICATION_BACKENDS = [
    "graphql_jwt.backends.JSONWebTokenBackend",
    "django.contrib.auth.backends.ModelBackend",
]
AUTH_USER_MODEL = "setup.User"

# Redis Config
REDIS_PORT = int(os.environ['REDIS_PORT'])
REDIS_PASSWORD = os.environ['REDIS_PASSWORD']
REDIS_HOST = "redis"  # "localhost" if DEBUG else "redis"

# RQ Config
RQ_QUEUES = {

    'high-python': {
        'HOST': REDIS_HOST,
        'PORT': 6379,
        'DB': 0,
        'PASSWORD': REDIS_PASSWORD,
        'DEFAULT_TIMEOUT': 60 * 60 * 24 * 14,
        'DEFAULT_RESULT_TTL': 60 * 60 * 24 * 3,
    },
    'default-python': {
        'HOST': REDIS_HOST,
        'PORT': 6379,
        'DB': 0,
        'PASSWORD': REDIS_PASSWORD,
        'DEFAULT_TIMEOUT': 60 * 60 * 24 * 14,
        'DEFAULT_RESULT_TTL': 60 * 60 * 24 * 3,
    },
}
