"""
Django settings for github_scraper project.

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

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

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

from typing import Dict, Any, TextIO, List, Union

# Define Config type for the configuration pulled from `config.json`
Config = Dict[str, Any]

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR: Path = Path(__file__).resolve().parent.parent

# "Secret" configuration dictionary
config: Config = {}

# Load configuration file
try:
    data_file: TextIO
    with open(BASE_DIR / 'settings' / 'config.json') as data_file:
        config = json.load(data_file)
except IOError:
    if 'SKIP_CONFIG' not in os.environ:
        sys.exit('You need to setup the config data file (see the `config_template.json` file.)')


# Application definition
INSTALLED_APPS: List[str] = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

# Third party apps
INSTALLED_APPS.extend([
])

# Project defined apps
INSTALLED_APPS.extend([
    'search_interface.apps.SearchInterfaceConfig',
])

MIDDLEWARE: List[str] = [
    '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'
]

ROOT_URLCONF: str = 'github_talent_search.urls'

TEMPLATES: List[Dict[str, Any]] = [
    {
        '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: str = 'github_talent_search.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES: Dict[str, Dict[str, Union[str, int, Dict, List]]] = {}
for database in config.get('databases', []):
    DATABASES[database.get('connection_name')] = {
        'NAME': database.get('database_name'),
        'ENGINE': database.get('engine'),
        'USER': database.get('user', ''),
        'PASSWORD': database.get('password', ''),
        'HOST': database.get('host', ''),
        'PORT': database.get('port', ''),
        'OPTIONS': database.get('options', {})
    }


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS: List[Dict[str, str]] = [
    {
        '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',
    },
]

# Logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'console',
        },
    },
    'loggers': {
        '': {
            'level': 'DEBUG',
            'handlers': ['console'],
        },
    },
}

# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE: str = 'en-us'

TIME_ZONE: str = 'UTC'

USE_I18N: bool = True

USE_L10N: bool = True

USE_TZ: bool = True


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

static_config: Dict = config.get('static', {})
STATIC_ROOT: str = static_config.get('root', '')
STATIC_URL: str = static_config.get('url', '/static/')

GITHUB_TOKEN: str = config.get('github_oauth_token')

INTERNAL_IPS = ['127.0.0.1', ]
