"""
Django settings for yasanta project.

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

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

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

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

try:
    exec(open('/etc/secret_settings.py').read())
except IOError:
    pass

import yenv
import blackbox
from django_yauth.settings import *  # noqa ignore=F401
YAUTH_TYPE = 'intranet'
YAUTH_USE_SITES = False
YAUTH_PASSPORT_FIELDS = [blackbox.FIELD_LANGUAGE, blackbox.FIELD_LOGIN]
YAUTH_USE_NATIVE_USER = True
YAUTH_CREATE_USER_ON_ACCESS = True

if yenv.type == 'development':
    AUTHENTICATION_BACKENDS = [
        'django_yauth.authentication_mechanisms.dev.UserFromHttpHeaderAuthBackend',
        'django_yauth.authentication_mechanisms.dev.UserFromCookieAuthBackend',
        'django_yauth.authentication_mechanisms.dev.UserFromOsEnvAuthBackend',
    ]
else:
    AUTHENTICATION_BACKENDS = [
        'django_yauth.authentication_mechanisms.cookie.Mechanism',
        'django_yauth.authentication_mechanisms.oauth.Mechanism',
    ]

DEBUG = True

STATIC_URL = '/adminstatic/'

if yenv.type == 'production':
    DEBUG = False
    STAFF_HOST = 'https://staff.yandex-team.ru'
    STAFF_API_HOST = 'https://staff-api.yandex-team.ru'
else:
    DEBUG = bool(int(os.getenv('DJANGO_DEBUG', 1)))
    STAFF_HOST = 'https://staff.test.yandex-team.ru'
    STAFF_API_HOST = 'https://staff-api.test.yandex-team.ru'

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

if yenv.type == 'development':
    SECRET_KEY = 'test_secret_key'
    STAFF_HOST = ''
    STAFF_API_HOST = ''
    DB_PASSWORD = 'TEST_DB_PASSWORD'
    OAUTH_TOKEN = 'TEST_OAUTH_TOKEN'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'file': {'()': 'ylog.FileFormatter'},
        'json': {'()': 'ylog.format.QloudJsonFormatter'},
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': os.getenv('LOG_FORMAT', 'json'),
        },
    },
    'loggers': {
        'django': {
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
            'handlers': ['console'],
            'propagate': True,
        },
        'requests': {
            'level': 'ERROR',
            'handlers': ['console'],
            'propagate': True,
        },
        'py.warnings': {
            'level': 'ERROR',
            'handlers': ['console'],
            'propagate': True,
        },
    },
    'root': {
        'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        'handlers': ['console'],
    },
}


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/


ALLOWED_HOSTS = [
    '.yandex-team.ru',
    '.yandex.net',
    '.yandex.ru',
]

if yenv.type == 'development':
    ALLOWED_HOSTS.append('localhost')

# Application definition

INSTALLED_APPS = (
    'django_yauth',
    'intranet.yasanta.backend.gifts',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)


MIDDLEWARE = (
    # 'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'intranet.yasanta.backend.middleware.UwsgiLogMiddleware',
    'intranet.yasanta.backend.middleware.PingMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'intranet.yasanta.backend.middleware.AuthMiddleware',
    'django_yauth.middleware.YandexAuthMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # 'django.contrib.auth.middleware.AuthenticationMiddleware',
    # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'intranet.yasanta.backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 'DIRS': ['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',
            ],
        },
    },
]

WSGI_APPLICATION = 'intranet.yasanta.backend.wsgi.application'


if yenv.type != 'development':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'HOST': os.getenv(
                'DB_HOSTS',
                ','.join([
                    'myt-0gqg1r33dn2d6dnl.db.yandex.net',
                    'sas-97e9vz38svls51n8.db.yandex.net',
                    'vla-kvc2nxr07f4wl3p1.db.yandex.net',
                ])
            ),
            'PORT': 6432,
            'USER': 'gifts',
            'PASSWORD': os.getenv('DB_PASS', ''),
            'NAME': os.getenv('DB_NAME', 'gifts_prod_pg_db'),
            'ATOMIC_REQUESTS': True,
            'CONN_MAX_AGE': 600,
            'OPTIONS': {
                'sslmode': 'verify-full',
                'sslrootcert': '/etc/allCAs.pem',
                'connect_timeout': 2,
                'target_session_attrs': 'read-write',
            },
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'HOST': 'database',
            'PORT': 5432,
            'USER': 'gifts',
            'PASSWORD': 'gifts',
            'NAME': os.getenv('DB_NAME', 'gifts'),
            'ATOMIC_REQUESTS': True,
            'CONN_MAX_AGE': 600,
            'OPTIONS': {
                'connect_timeout': 2,
            },
        }
    }


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
