# Django settings for polynum project.

import os
import os.path
import django.conf.global_settings as DEFAULT_SETTINGS
from django.core.urlresolvers import reverse_lazy
from logging.handlers import SysLogHandler
import pkg_resources

PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '.')

DEBUG = False
DEBUG_TOOLBAR = False
TEMPLATE_DEBUG = False

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/tmp/polynum.db',              # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# 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.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Paris'

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

SITE_ID = 1

SITE_URL = 'http://polynum.example.com'

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

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
        '/var/lib/polynum/extra-static/',
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'ni9p7j88=*)b$9m#4ihud35n&amp;s^dtd5ml*4stbuth7=*93-m=y'

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

MIDDLEWARE_CLASSES = (
    'entrouvert.djommon.middleware.UserInTracebackMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

INTERNAL_IPS = ('127.0.0.1',)

ROOT_URLCONF = 'polynum.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'polynum.wsgi.application'

TEMPLATE_DIRS = (
    '/var/lib/polynum/templates/',
    os.path.join(PROJECT_ROOT, "templates"),
)

TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
        'sekizai.context_processors.sekizai',
        'django.core.context_processors.request', # needed by django-admin-tools
        )

INSTALLED_APPS = (
    # note: 'south' will be added here only if database is not sqlite (see below)
    #
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.formtools',
    #'django.contrib.admindocs',
    'sekizai',
    'crispy_forms',
    'polynum.pages',
    'polynum.base',
    'polynum.request',
    'polynum.entity',
    'polynum.editor',
    'polynum.delegation',
    'polynum.oai',
    # admin
    'admin_tools',
    'admin_tools.dashboard',
    'django.contrib.admin',
    'ajax_select',
)

# Load plugin applications
for entrypoint in pkg_resources.iter_entry_points('polynum_plugin'):
    plugin_class = entrypoint.load()
    plugin = plugin_class()
    INSTALLED_APPS += tuple(plugin.get_applications())
    if hasattr(plugin, 'get_template_dirs'):
        TEMPLATE_DIRS += tuple(plugin.get_template_dirs())


# From http://django-crispy-forms.readthedocs.org/en/d-0/install.html
CRISPY_TEMPLATE_PACK = 'bootstrap'

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'formatters': {
        'syslog': {
            'format': 'polynum(pid=%(process)d) %(levelname)s %(message)s'
        },
    },
    'handlers': {
        'syslog': {
            'level':'INFO',
            'class':'logging.handlers.SysLogHandler', 
            'formatter': 'syslog',
            'facility': SysLogHandler.LOG_LOCAL0,
            'address': '/dev/log',
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': [],
        }
    },
    'loggers': {
        '': {
            'handlers': ['mail_admins', 'syslog', 'console' ],
            'level': 'INFO',
        },
    },
}

AUTHENTICATION_BACKENDS = ('polynum.base.backends.ModelBackend',)
AUTH_PROFILE_MODULE = 'base.PolynumProfile'
CAS_SERVER_URL = None  # 'https://www.ent.dauphine.fr/cas/'

# django-admin-tools
# see http://django-admin-tools.readthedocs.org/en/latest/customization.html
ADMIN_TOOLS_INDEX_DASHBOARD = {
    'polynum.base.admin.site': 'polynum.dashboard.CustomIndexDashboard',
}
ADMIN_TOOLS_APP_INDEX_DASHBOARD = {
    'polynum.base.admin.site': 'polynum.dashboard.CustomAppIndexDashboard',
}


# Session cookies
SESSION_COOKIE_AGE = 3600*24 # 1 day
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

# File upload handlers
FILE_UPLOAD_HANDLERS = ("django.core.files.uploadhandler.TemporaryFileUploadHandler",)

try:
    from local_settings import *
except ImportError:
    pass

# use South, unless if database is sqlite3
if DATABASES['default']['ENGINE'] != 'django.db.backends.sqlite3' or 'FORCE_SOUTH' in os.environ:
    INSTALLED_APPS = ('south',) + INSTALLED_APPS

# CAS

if CAS_SERVER_URL:
    AUTHENTICATION_BACKENDS += ( 'polynum.base.backends.CASBackend', )
    MIDDLEWARE_CLASSES += ( 'django_cas.middleware.CASMiddleware', )

LOGIN_REDIRECT_URL = reverse_lazy('list_request')

# AJAX Lookup
AJAX_LOOKUP_CHANNELS = {
        'ldap-users': ('polynum.base.lookup_channels', 'LDAPLookup'),
}

if DEBUG:
    TEMPLATE_DEBUG = True 
    LOGGING['loggers']['']['level'] = 'DEBUG'

if DEBUG and DEBUG_TOOLBAR:
    MIDDLEWARE_CLASSES += (
        'debug_toolbar.middleware.DebugToolbarMiddleware',
    )
    INSTALLED_APPS += (
        'debug_toolbar',
    )
    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
    }

try:
    from gunicorn import version_info
    if version_info > (0,14,0):
        INSTALLED_APPS += (
            'gunicorn',
        )
    del version_info
except:
    pass

