"""
Django settings for CalibreWebCompanion project.

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

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
import json
import logging

logger = logging.getLogger(__name__)

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

with open(BASE_DIR + "/settings.json", "r") as userfile:
    usersettings = json.load(userfile)
    CALIBRE_DIR = os.path.abspath(usersettings["CALIBRE_DIR"])
    SECRET_KEY = usersettings["SECRET_KEY"]
    ALLOWED_HOSTS = usersettings["ALLOWED_HOSTS"]
    INTERNAL_IPS = usersettings["INTERNAL_IPS"]
    DEBUG = usersettings["DEBUG"]


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


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

# optimisation stuff ###############################################3
#                                                                    #
CONN_MAX_AGE = 60 * 5

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
        "TIMEOUT": 60 * 5,

    }
}

##                                                                    ##
########################################################################
##                    STATIC FILES                                    ##

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

STATICFILES_DIRS = [
    # os.path.abspath(CALIBRE_DIR),
    # '/static/',
]

STATIC_URL = '/static/'

STATIC_ROOT = BASE_DIR + "/static/"
##                                                                     ##
#########################################################################
# LOGGING



logfile = usersettings["LOGFOLDER"] + "django.log"
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "root": {"level": "INFO", "handlers": ["file"]},
    "handlers": {
        "file": {
            "level": "INFO",
            "class": "logging.FileHandler",
            "filename": logfile,
            "formatter": "app",
        },
    },
    "loggers": {
        "django": {
            "handlers": ["file"],
            "level": "INFO",
            "propagate": True
        },
    },
    "formatters": {
        "app": {
            "format": (
                u"%(asctime)s [%(levelname)-8s] "
                "(%(module)s.%(funcName)s) %(message)s"
            ),
            "datefmt": "%Y-%m-%d %H:%M:%S",
        },
    },
}


##                                                                    ##
########################################################################
##                    DERUG                                           ##

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


DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.timer.TimerPanel',
    'debug_toolbar.panels.headers.HeadersPanel',
    'debug_toolbar.panels.request.RequestPanel',
    'debug_toolbar.panels.sql.SQLPanel',
    'debug_toolbar.panels.templates.TemplatesPanel',
    'debug_toolbar.panels.cache.CachePanel',
    'debug_toolbar.panels.signals.SignalsPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
    'debug_toolbar.panels.profiling.ProfilingPanel',
]


##                                                                    ##
########################################################################
##                    DERUG                                           ##


# SILKY_PYTHON_PROFILER = True
# SILKY_PYTHON_PROFILER_BINARY = True
# SILKY_PYTHON_PROFILER_RESULT_PATH = BASE_DIR + "/profiler"
# SILKY_META = True

LOGIN_REDIRECT_URL = '/books'

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "library",
    # "silk", # DEBUG/profilling purposes
    # 'debug_toolbar', # DEBUG  purposes
]

MIDDLEWARE = [
    # 'silk.middleware.SilkyMiddleware', # DEBUG/profiling purposes
    # 'debug_toolbar.middleware.DebugToolbarMiddleware', # DEBUG purposes
    'django.middleware.cache.UpdateCacheMiddleware',  # cache
    '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',
    'django.middleware.cache.FetchFromCacheMiddleware',  # cache
]
##                                                                    ##
########################################################################


ROOT_URLCONF = 'CalibreWebCompanion.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',
                "library.context_processors.filters"
            ],
        },
    },
]

WSGI_APPLICATION = 'CalibreWebCompanion.wsgi.application'

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

if usersettings["ISDOCKER"]:
    defaultdb_path = "/usr/src/app/data/"
else:
    defaultdb_path = BASE_DIR

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


DATABASE_ROUTERS = ["db_routers.CalibreRouter", "db_routers.DjangoRouter"]

# 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 = 'America/Paramaribo'

USE_I18N = True

USE_L10N = True

USE_TZ = True
