# -*- coding: utf-8 -*-
import os
import django.conf.global_settings
gettext_noop = lambda s: s

PROJECT_PATH = os.path.join(os.path.dirname(__file__), '..')
PROJECT_NAME = 'docbow'

# boolean settings
__ENVIRONMENT_DEFAULTS = dict(
        # booleans
        DEBUG=False,
        DEBUG_PROPAGATE_EXCEPTIONS=False,
        USE_DEBUG_TOOLBAR=False,
        TEMPLATE_DEBUG=False,
        # paths
        STATIC_ROOT='/var/lib/%s/static' % 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',
        TEMPLATE_DIRS=('/var/lib/%s/templates' % PROJECT_NAME,),
        STATICFILES_DIRS=('/var/lib/%s/extra-static/' % PROJECT_NAME,),
        GRAPPELLI_ADMIN_TITLE=u"Plate-forme sécurisée d'échange de documents",
        FILE_PER_PAGE=30,
        TINYMCE_SPELLCHECKER=True,
        TINYMCE_JS_URL="/static/js/tiny_mce/tiny_mce_src.js",
        TINYMCE_COMPRESSOR=True,
        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(PROJECT_PATH, 'docbow_project', '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' ),
        AUTH_LDAP_SERVER_URI='ldaps://ldap.libre-entreprise.org:636',
        AUTH_LDAP_BIND_DN='uid=admin,ou=people,o=entrouvert,ou=companies,o=libre-entreprise',
        AUTH_LDAP_BIND_PASSWORD='',
        INTERNAL_IPS=('127.0.0.1','82.234.244.169'),
        ADMINS=(),
        SOUTH_TESTS_MIGRATE=True,
        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/%s/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,
        TEMPLATE_CONTEXT_PROCESSORS=django.conf.global_settings.TEMPLATE_CONTEXT_PROCESSORS+('django.core.context_processors.request',),
        DATE_INPUT_FORMATS=('%d/%m/%Y', '%Y-%m-%d'),
        CRISPY_TEMPLATE_PACK='uni_form',
)

for key, default in __ENVIRONMENT_DEFAULTS.iteritems():
    try:
        value = os.environ[key]
        if default is True or default is False:
            if value.isdigit():
                value = bool(int(value))
            else:
                value = value.lower() in ('yes', 'true', 'y')
        elif isinstance(default, (tuple, list)):
            value = [ x.strip() for x in value.split(':')]
            if len(default) or key in ('ADMINS',):
                if key in ('ADMINS',) or isinstance(default[0], (tuple, list)):
                    value = [ x.split(';') for x in value ]
                elif isinstance(default[0]. unicode):
                    value = [ unicode(x, 'utf8') for x in value ]
        elif isinstance(default, unicode):
            value = unicode(value, 'utf8')
    except KeyError:
        value = default
    globals()[key] = value

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': os.environ.get('DATABASE_ENGINE', 'django.db.backends.sqlite3'),
        'NAME': os.environ.get('DATABASE_NAME', os.path.join(PROJECT_PATH, PROJECT_NAME + '.db')),
    }
}

# Hey Entr'ouvert is in France !!

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

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

MIDDLEWARE_CLASSES = (
    '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.transaction.TransactionMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'docbow_project.docbow.middleware.KeepUserAroundMiddleware',
    'django_journal.middleware.JournalMiddleware',
)

INSTALLED_APPS = (
    'docbow_project.docbow',
    'docbow_project.pfwb',
    'django_tables2',
    'grappelli',
    'django_journal',
    'crispy_forms',
    'tinymce',
    'south',
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
)

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

TINYMCE_DEFAULT_CONFIG = {
    'theme': "advanced",
}

import logging.handlers

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': 'entrouvert.logging.handlers.SysLogHandler', 
            'formatter': 'syslog_debug' if DEBUG else 'syslog',
            'facility': logging.handlers.SysLogHandler.LOG_LOCAL0,
            'address': '/dev/log',
            'max_length': 999,
            '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': [ 'mail_admins', 'syslog' ],
            'level': 'INFO',
            'propagate': False,
        },
        'south': {
            'handlers': [ 'mail_admins', 'syslog' ],
            'level': 'INFO',
            'propagate': False,
        },
        'docbow.mail_interface': {
            'handlers': [ 'mail_admins', 'syslog' ],
            'level': 'DEBUG' if DEBUG else 'INFO',
            'propagate': False,
        },
        'docbow': {
            'handlers': [ 'mail_admins', 'syslog' ],
            'level': 'DEBUG' if DEBUG else 'INFO',
            'propagate': False,
        },
        '': {
            'handlers': [ 'mail_admins', 'syslog' ],
            'level': 'DEBUG',
        },
    },
}

if DEBUG:
    for key, logger in LOGGING['loggers'].iteritems():
        logger['handlers'].append('console')

# LDAP backend configuration
try:
    import ldap
except ImportError:
    pass
else:
    from django_auth_ldap.config import LDAPSearch, GroupOfUniqueNamesType

    AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend',) + AUTHENTICATION_BACKENDS
    AUTH_LDAP_USER_SEARCH =  LDAPSearch("ou=people,o=entrouvert,ou=companies,o=libre-entreprise",
        ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
    AUTH_LDAP_GROUP_TYPE = GroupOfUniqueNamesType()
    AUTH_LDAP_GROUP_SEARCH = LDAPSearch("o=libre-entreprise",
                ldap.SCOPE_SUBTREE, "(objectClass=legroup)")
    AUTH_LDAP_USER_FLAGS_BY_GROUP = {
        "is_staff": "cn=ldapadmins,ou=groups,o=entrouvert,ou=companies,o=libre-entreprise",
        "is_superuser": "cn=ldapadmins,ou=groups,o=entrouvert,ou=companies,o=libre-entreprise",
    }
    AUTH_LDAP_USER_ATTR_MAP = {
        "first_name": "givenName",
        "last_name": "sn",
        "email": "mail"
    }

try:
    from local_settings import *
except ImportError, e:
    if 'local_settings' not in e.args[0]:
        raise

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

if USE_DEBUG_TOOLBAR:
    try:
        import debug_toolbar
        MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
        INSTALLED_APPS += ('debug_toolbar',)
        DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False }
    except ImportError:
        print "Debug toolbar missing, not loaded"

# 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
