# coding: utf-8

import os
import yenv
import socket
from datasources_config_wrapper import DatasourcesConfigWrapper

conf = DatasourcesConfigWrapper(prefix='libra', suppress_warning=True)

DEBUG = bool(int(os.getenv('DJANGO_DEBUG', yenv.type != 'production')))
TEMPLATE_DEBUG = DEBUG
FILE_CHARSET = 'utf-8'
INTERNAL_IPS = ('127.0.0.1')

ADMINS = ('lib@lib.yandex-team.ru',)
MANAGERS = ADMINS

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Moscow'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'ru-ru'

SITE_ID = 1


# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False

VAR_PATH = '/var/'

MEDIA_ROOT = '/src/media/'
MEDIA_URL = '/src/media/'
STATIC_URL = '/admin/media/'

SECRET_KEY = 'b9s%626%6nwu584@2uc+e-@^ae+*s$07qa4&1rq9l*ni26^nm9'

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.contrib.messages.context_processors.messages",
)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.app_directories.Loader',
    'django.template.loaders.filesystem.Loader',
)

# Email settings
EMAIL_BACKEND = 'libra.mail_app.backends.CustomEmailBackend'
EMAIL_HOST = 'outbound-relay.yandex.net'
EMAIL_PORT = '25'

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django_replicated.middleware.ReplicationMiddleware',
    'django_alive.middleware.AliveMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django_xscript.middleware.XScriptMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django_yauth.middleware.YandexAuthMiddleware',
)

ROOT_URLCONF = 'libra.urls'

TEMPLATE_DIRS = (
    os.path.abspath(os.path.join('/src/libra/', './templates')),
    os.path.abspath(os.path.join('/src/libra/', './books/templates')),
    os.path.abspath(os.path.join('/src/libra/', './crash_course/templates')),
    os.path.abspath(os.path.join('/src/libra/', './devices/templates')),
    os.path.abspath(os.path.join('/src/libra/', './kiosks/templates')),
)

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django_extensions',
    'django_intranet_stuff',
    'django_russian',
    'libra.api',
    'libra.books',
    'libra.devices',
    'libra.kiosks',
    'libra.crash_course',
    'libra.tagging',
    'mptt',
    'south',
)


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

from django_yauth.settings import *
YAUTH_TYPE = 'intranet'
YAUTH_USE_SITES = False
YAUTH_USE_NATIVE_USER = True

USER_AGENT = 'lib.yandex-team.ru/1.0'

from django_intranet_stuff.settings import *
del PASSPORT_FIELDS


INTRANET_MODELS_STAFF = [
    'address',
    'address_en',
    'birthday',
    'car',
    'car_num',
    'created_at',
    'department',
    'domain',
    'employment',
    'en_name',
    'first_name',
    'first_name_en',
    'from_staff_id',
    'gender',
    'guid',
    'uid',
    'hide_birthday_year',
    'hide_middle_name',
    'id',
    'intranet_status',
    'is_big_boss',
    'is_dismissed',
    'join_at',
    'last_name',
    'last_name_en',
    'login',
    'login_ld',
    'login_mail',
    'middle_name',
    'mobile_phone',
    'modified_at',
    'native_lang',
    'normal_login',
    'office',
    'position',
    'position_en',
    'quit_at',
    'tz',
    'user',
    'wiki_name',
    'work_email',
    'work_phone',
]

INTRANET_MODELS = (
    'City',
    'Department',
    'DepartmentStaff',
    'DepartmentStaffCounter',
    'Office',
    'Staff',
)


# этушка
AT_CLUB_URL = "http://clubs.at.yandex-team.ru/books/replies.xml?item_no={item_no}"
AT_CLUB_ID = 4611686018427388015

# добавляет свои слова в словарь
import django_russian_forms

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': conf.mysql_master_host,
        'PORT': conf.mysql_master_port,
        'NAME': conf.mysql_master_name,
        'USER': conf.mysql_master_user,
        'PASSWORD': conf.mysql_master_password,
        'OPTIONS': {
            'connect_timeout': 2,
            'init_command': 'SET default_storage_engine=INNODB; SET names utf8mb4;',
            'charset': 'utf8mb4',
        }
    },

    'slave1': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': conf.mysql_slave_host,
        'PORT': conf.mysql_slave_port,
        'NAME': conf.mysql_slave_name,
        'USER': conf.mysql_slave_user,
        'PASSWORD': conf.mysql_slave_password,
        'OPTIONS': {
            'connect_timeout': 2,
            'init_command': 'SET default_storage_engine=INNODB; SET names utf8mb4;',
            'charset': 'utf8mb4',
        }
    },

    'slave2': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': conf.mysql_slave2_host,
        'PORT': conf.mysql_slave2_port,
        'NAME': conf.mysql_slave2_name,
        'USER': conf.mysql_slave2_user,
        'PASSWORD': conf.mysql_slave2_password,
        'OPTIONS': {
            'connect_timeout': 2,
            'init_command': 'SET default_storage_engine=INNODB; SET names utf8mb4;',
            'charset': 'utf8mb4',
        }
    },

}

DATABASE_SLAVES = ['slave1', 'slave2']
DATABASE_ROUTERS = ['django_replicated.ReplicationRouter']

YT_TOKEN = conf.yt_token
YLOCK = {
    'backend': 'yt',
    'prefix': '//home/cia/libra/{}'.format(os.environ.get('QLOUD_ENVIRONMENT', 'unknown')),
    'token': YT_TOKEN,
}

ELLIPTICS_PRIVATE_URL = conf.elliptics_private_url
RFID_ACCESS_TOKEN = conf.rfid_access_token
YARU_ACCESS_TOKEN = conf.at_access_token
MDS_HOST = conf.mds_read_url
MDS_WRITE_HOST = conf.mds_write_url
MDS_ACCESS_TOKEN = conf.mds_access_token
MDS_NAMESPACE = 'libra'

ELLIPTICS_PREFIX = 'libra'
ELLIPTICS_PUBLIC_URL = '/elliptics/'

LOCK_PATH = '/var/lock/yandex-tools-libra'
MEDIA_ROOT = '/src/media'

# XScript
XSCRIPT_CONFIG = '/src/libra/xscript-offline-dev.conf'
XSCRIPT_CONFIG_FILE = '/src/libra/xscript-offline-dev.conf'
XSCRIPT_DOCUMENT_ROOT = MEDIA_ROOT

# Разработческие настройки XScript. Они переопределяются на продакшне и в тестинге при установке пакета
XSCRIPT_XSLT_FILE = os.path.join(MEDIA_ROOT, 'data.xsl')


import datetime
# Дата выкатки релиза с исправлением бага с датами.
# После этого события датам в истории можно верить.
DATE_BUGFIX_RELEASE = datetime.date(2012, 5, 16)

# Время, в течении которого разрешено держать у себя книгу (обратный интервал)
# В нормальных условиях должен быть равен -9 неделям (2 месяца)
BOOK_HOLD_PERIOD = datetime.timedelta(weeks=-9)

RETURN_BOOK_FROM = 'library_return@yandex-team.ru'

# URL RSS ленты этушки, для показа новостей на морде библиотеки
# SERVICE_BLOG_RSS_URL = 'http://clubs.at.yandex-team.ru/libra/rss/posts.xml?tag=2315'

BOT_URL = "http://bot.yandex-team.ru/api/moblib.php"

CENTER_RPC_USER = '_rpc_libra'
CENTER_RPC_PASSWORD = 'eKBQ2RKtCXsuZDGfecWTew8T'


MAX_TAG_LENGTH = 255


if yenv.type == 'production':
    DEFAULT_ORDER_EXECUTER = [u'"Библиотека" <buybook@yandex-team.ru>',]

    CENTER_MASTER = 'center.yandex-team.ru'
    CENTER_URL = "http://center.yandex-team.ru/"
    STAFF_URL = "http://staff.yandex-team.ru/"
    RFID_PROVIDER_URL = 'https://staff.yandex-team.ru/'

    SERVER_EMAIL = 'lib@lib.yandex-team.ru'
    SERVER_HOST = 'https://lib.yandex-team.ru'

    LONG_TIME_BUSY_MAIL = True
    RETURN_BOOK_MAIL = True

else:
    DEFAULT_ORDER_EXECUTER = ['mtest@yandex-team.ru',]

    CENTER_MASTER = 'center.prestable.yandex-team.ru'
    CENTER_URL = "http://center.test.yandex-team.ru/"
    STAFF_URL = "http://staff.test.yandex-team.ru/"
    RFID_PROVIDER_URL = 'https://staff.test.yandex-team.ru/'

    SERVER_EMAIL = 'lib@lib.test.yandex-team.ru'
    SERVER_HOST = 'https://lib.test.yandex-team.ru'

    LONG_TIME_BUSY_MAIL = os.getenv('LONG_TIME_BUSY_MAIL', False),
    RETURN_BOOK_MAIL = os.getenv('RETURN_BOOK_MAIL', False),
    ROUTE_ALL_MAIL_TO = 'mtest@yandex-team.ru'
