# -*- coding: utf-8 -*-
import os
import logging.handlers

from django.core.exceptions import ImproperlyConfigured

gettext_noop = lambda s: s

BASE_DIR = os.path.dirname(__file__)
PROJECT_NAME = 'docbow'

# booleans
DEBUG = False
DEBUG_PROPAGATE_EXCEPTIONS = False
# paths
STATIC_ROOT = '/var/lib/%s/collectstatic' % PROJECT_NAME
STATIC_URL = '/static/'
MEDIA_ROOT = '/var/lib/%s/media' % PROJECT_NAME
MEDIA_URL = '/media/'
# i18n/l18n
TIME_ZONE = 'Europe/Paris'
LANGUAGE_CODE = 'fr'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
# core
ROOT_URLCONF = 'docbow_project.urls'
STATICFILES_DIRS = ('/var/lib/%s/static/' % PROJECT_NAME,)
FILE_PER_PAGE = 30
DO_NOT_SEND_GROUPS = (
    u'Administrateurs des groupes',
    u'Administrateurs des types de document',
    u'Administrateurs des utilisateurs',
    u"Utilisateurs de l'application",
)
CONTACT_GROUPS = (u'Contact « Administrateur du système »',)
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
DEFAULT_FROM_EMAIL = 'admin@example.com'
CONTACT_SUBJECT_PREFIX = 'Contact depuis docbow: '
ALLOWED_HOSTS = ['*']
LOGIN_REDIRECT_URL = '/inbox'
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
AUTHENTICATION_BACKENDS = (
    'docbow_project.docbow.auth_backend.DelegationAuthBackend',
    'django.contrib.auth.backends.ModelBackend',
)
INTERNAL_IPS = ('127.0.0.1', '82.234.244.169')
ADMINS = ()
SECRET_KEY = None
OVH_SMS_ACCOUNT = 'sms-db26857-1'
OVH_SMS_LOGIN = 'pfwb'
OVH_SMS_PASSWORD = ''
OVH_SMS_FROM = 'Dauvergne'
DOCBOW_SMS_CARRIER_CLASS = 'docbow_project.docbow.sms_carrier_ovh.OVHSMSCarrier'
DOCBOW_ORGANIZATION_SHORT = 'PFWB'
DOCBOW_ORGANIZATION = u'Parlement de la Fédération Wallonie-Bruxelles'
DOCBOW_NOTIFIERS = (
    'docbow_project.docbow.notification.MailNotifier',
    'docbow_project.docbow.notification.SMSNotifier',
)
DOCBOW_PFWB_GED_DIRECTORY = '/var/lib/docbow/ged/'
DOCBOW_PFWB_SENDMAIL_DEFAULT_TYPE_ID = None
DOCBOW_PFWB_SENDMAIL_DEFAULT_TYPE_NAME = u'Divers'
DOCBOW_PFWB_SENDMAIL_TABELLIO_EXPEDITION_EMAIL = 'commande.documents@pfwb.be'
DOCBOW_PFWB_SENDMAIL_TABELLIO_EXPEDITION_USER_ID = None
DOCBOW_PFWB_SENDMAIL_ATTACHED_FILE_EMAIL = 'dontknow@pfwb.be'
DOCBOW_PFWB_SENDMAIL_ATTACHED_FILE_USER_ID = None
DATE_INPUT_FORMATS = ('%d/%m/%Y', '%Y-%m-%d')
DOCBOW_MAX_FILE_SIZE = 10 * 1024 * 1024
DOCBOW_PRIVATE_DOCUMENTS = False
DOCBOW_BASE_URL = 'http://localhost:8000'
PLATFORM = 'prod'
DOCBOW_EDIT_EMAIL = False
EMAIL_HOST = 'localhost'
SECURE_PROXY_SSL_HEADER = ()
SESSION_COOKIE_AGE = 7200
SILENCED_SYSTEM_CHECKS = ['admin.E130', 'models.W042']

TEST_RUNNER = 'django.test.runner.DiscoverRunner'


MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'docbow',
    }
}

# Hey Entr'ouvert is in France !!

LANGUAGES = (('fr', gettext_noop('French')),)


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['/var/lib/%s/templates' % PROJECT_NAME, os.path.join(BASE_DIR, 'docbow', 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.request',
                'docbow_project.docbow.context_processors.settings_url_processor',
            ],
        },
    },
]


ATOMIC_REQUESTS = True

MIDDLEWARE = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'docbow_project.docbow.middleware.KeepUserAroundMiddleware',
    'django_journal.middleware.JournalMiddleware',
    'watson.middleware.SearchContextMiddleware',
)


INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'watson',
    'django.contrib.admin',
    'django_tables2',
    'django_journal',
    'docbow_project.humantime',
    'docbow_project.docbow',
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'syslog': {
            'format': PROJECT_NAME + '(pid=%(process)d) %(levelname)s %(name)s: %(message)s',
        },
        'syslog_debug': {
            'format': PROJECT_NAME
            + '(pid=%(process)d) %(levelname)s %(asctime)s t_%(thread)s %(name)s: %(message)s',
        },
    },
    'handlers': {
        'syslog': {
            'level': 'DEBUG',
            'class': 'logging.handlers.SysLogHandler',
            'formatter': 'syslog_debug' if DEBUG else 'syslog',
            'facility': logging.handlers.SysLogHandler.LOG_LOCAL0,
            'address': '/dev/log',
            'filters': [],
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': [],
            'include_html': True,
        },
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'syslog_debug',
            'level': 'DEBUG',
        },
    },
    'loggers': {
        'django.db': {
            'handlers': [],
            'level': 'INFO',
            'propagate': True,
        },
        'django.request': {
            'handlers': [],
            'propagate': True,
        },
        '': {
            'handlers': ['syslog'],
            'level': 'INFO',
        },
    },
}

if DEBUG:
    LOGGING['loggers']['']['level'] = 'DEBUG'
    LOGGING['loggers']['']['handlers'].append('console')


HELP_DIR = '/usr/share/doc/docbow/help'

for logger in LOGGING['loggers'].values():
    if 'syslog' in logger['handlers']:
        logger['handlers'].append('mail_admins')

if DEBUG and not globals()['SECRET_KEY']:
    SECRET_KEY = 'coin'

# syntax checks
for admin in ADMINS:
    assert len(admin) == 2, (
        'ADMINS setting must be a colon separated list of name and emails separated by a semi-colon: %s'
        % ADMINS
    )
    assert '@' in admin[1], 'ADMINS setting pairs second value must be emails: %s' % ADMINS


LOGOUT_URL = '/accounts/logout/'

# path to mbox file to store a copy of all mails piped to the sendmail
# management command.
SENDMAIL_DEBUG_MBOX = None

# If True every file of a document can be downloaded in a zip archive
ZIP_DOWNLOAD = False

# Duration of trash retention in days
TRASH_DURATION = 0

EXTRA_SENDERS = False


local_settings_file = os.environ.get('DOCBOW_SETTINGS_FILE', 'local_settings.py')
if os.path.exists(local_settings_file):
    with open(local_settings_file) as f:
        exec(f.read())
