"""
Django settings for project project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os
from .environments import EnvironmentFileToDict, EnvironmentOsToDict

gettext = lambda s: s

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

# Инициализируем переменные окружения.
ENV_DICT = {}

# Загружаем переменные из файла.
ENV_FILE_FROM_FILE = EnvironmentFileToDict()
ENV_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".env")

if os.path.exists(ENV_FILE):
    ENV_FILE_FROM_FILE.load(ENV_FILE)
    ENV_DICT.update(ENV_FILE_FROM_FILE)

# Загружаем переменные из ОС.
ENV_DICT_FROM_OS = EnvironmentOsToDict()
ENV_DICT_FROM_OS.load()

ENV_DICT.update(ENV_DICT_FROM_OS)

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ENV_DICT['SECRET_KEY']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = ENV_DICT.get('DEBUG', True)
# Спецом что бы не стартовала без переменной.
ENVIRONMENT = ENV_DICT['ENVIRONMENT']

ALLOWED_HOSTS = ['*']

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

MEDIA_URL = ENV_DICT.get('MEDIA_URL', '/media/')
STATIC_URL = ENV_DICT.get('STATIC_URL', '/static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

INSTALLED_APPS = [

    'modelcluster',
    'taggit',

    # Django
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.sitemaps',

    # Vendors
    'corsheaders',
    'ordered_model',
    'mptt',
    'parler',
    'rest_framework',

    # Projects
    'apps.for_people.apps.CoreConfig',
]

FILER_ENABLE_PERMISSIONS = False

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

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'), 'templates'],
        'APP_DIRS': False,
        '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',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.csrf',
                'django.template.context_processors.tz',
                'django.template.context_processors.static',
            ],
            'loaders': [
                # 'admin_tools.template_loaders.Loader',
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': ENV_DICT.get('POSTGRES_DB'),
        'USER': ENV_DICT.get('POSTGRES_USER'),
        'PASSWORD': ENV_DICT.get('POSTGRES_PASSWORD'),
        'HOST': ENV_DICT['POSTGRES_HOST'],
        'PORT': ENV_DICT.get('POSTGRES_PORT', 5432)
    },
}

NORECAPTCHA_SITE_KEY = ENV_DICT.get('NORECAPTCHA_SITE_KEY')
NORECAPTCHA_SECRET_KEY = ENV_DICT.get('NORECAPTCHA_SECRET_KEY')

DEFAULT_FROM_EMAIL = ENV_DICT.get('DEFAULT_FROM_EMAIL', 'noreply@for.people.ru')
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = ENV_DICT.get('EMAIL_USE_TLS')
EMAIL_HOST = ENV_DICT.get('EMAIL_HOST')
EMAIL_PORT = ENV_DICT.get('EMAIL_PORT')
EMAIL_HOST_USER = ENV_DICT.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = ENV_DICT.get('EMAIL_HOST_PASSWORD')

MIGRATION_MODULES = {

}

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 100
}

LOGGING = {
    "version": 1,
    "disable_existing_loggers": True,
    "formatters": {
        "verbose": {
            "format": "%(levelname)s %(asctime)s %(process)d %(module)s %(message)s"
        },
        "simple": {
            "format": "%(levelname)s %(message)s"
        },
    },
    "handlers": {
        "file": {
            "level": ENV_DICT.get('HANDLER_LEVEL_FILE', 'ERROR'),
            "class": "logging.FileHandler",
            "filename": os.path.join(BASE_DIR, 'log', 'django.log'),
            "formatter": "verbose",
        },
        "console": {
            "level": ENV_DICT.get('HANDLER_LEVEL_CONSOLE', 'WARNING'),
            "class": "logging.StreamHandler",
            "formatter": "verbose",
        },
        "mail_admins": {
            "level": ENV_DICT.get('HANDLER_LEVEL_MAIL', 'ERROR'),
            "class": "django.utils.log.AdminEmailHandler"
        },
    },
    "loggers": {
        "django": {
            "handlers": ["file", "mail_admins"],
            "propagate": True,
            "level": ENV_DICT.get('LOGGER_LEVEL_DJANGO', 'ERROR'),
        },
        "django.request": {
            "handlers": ["file", "console"],
            "level": ENV_DICT.get('LOGGER_LEVEL_REQUEST', 'ERROR'),
            "propagate": True,
        },
        "django.db.backends": {
            "handlers": ["file", "console"],
            "level": ENV_DICT.get('LOGGER_LEVEL_DB', 'ERROR'),
        },
        "apps": {
            "handlers": ["file", "console", "mail_admins"],
            "level": ENV_DICT.get('LOGGER_LEVEL_APPS', 'ERROR'),
        },
    },
}

SITE_ID = 1

###############
# Авторизация #
###############


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 = [
    'django.contrib.auth.backends.ModelBackend',
]

LOGIN_URL = 'api:users:login'


########################
# Internationalization #
########################

LANGUAGE_CODE = 'ru-RU'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale')
]

PARLER_DEFAULT_LANGUAGE_CODE = 'ru'
PARLER_LANGUAGES = {
    None: (
        {'code': 'ru'},
        {'code': 'en'},
    ),
    'default': {
        'fallback': 'ru',
        'hide_untranslated': True,
    }
}
LANGUAGES = (
    ('en', gettext('Английский')),
    ('ru', gettext('Русский')),
)

if ENV_DICT.get('ENVIRONMENT', None) == 'development':
    # Даем доступ дл фронта.
    from corsheaders.defaults import default_headers, default_methods

    CORS_ALLOW_CREDENTIALS = True
    CORS_ALLOW_METHODS = default_methods
    CORS_ALLOW_HEADERS = ['X-Forwarded-Proto', 'X-Forwarded-Host', 'X-Api-Key']
    CORS_ALLOW_HEADERS.extend(default_headers)

    CORS_DOMAINS = ENV_DICT.get('CORS_DOMAINS').split(',')
    CORS_ORIGIN_WHITELIST = CORS_DOMAINS
    CSRF_TRUSTED_ORIGINS = CORS_DOMAINS
    INSTALLED_APPS = INSTALLED_APPS + [
        'django_extensions',
    ]
