"""
Django settings for mysite project.

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

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

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

PROJECT_ROOT = os.path.abspath(
    os.path.join(os.path.dirname(__file__), ".."),
)

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&t&czmg=xh$7*d!5eagw!=_v@kfm9e*t78pnz12%ql^(r)9))h'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# TEMPLATE_DEBUG = True

ALLOWED_HOSTS = [
    'ck.ntuh.net',
    'dev',
    'dev18',
    'dev.xiao.tw',
    'localhost',
    '192.168.11.178',
]

ALLOWED_HOSTS = [ '*' ]

# Application definition

INSTALLED_APPS = (
                  
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
#     'autocomplete_light',
    # 'debug_toolbar.apps.DebugToolbarConfig',
    # 'cacheops',
    'dal',
    'dal_select2',
    'datatableview',
    'debug_toolbar',
    'djangobower',
    # 'django_python3_ldap',
    'django_tables2',

    'rest_framework',
    'rest_framework_datatables',
    # 'schedule',

    'ck',
    'calculator',
    'nsclc',
    'mssql_ntuh',
    
)

# MIDDLEWARE_CLASSES = (
MIDDLEWARE = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    'debug_toolbar.middleware.DebugToolbarMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
}

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Taipei'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_ROOT = '/home/cks/public_html/static'

BOWER_COMPONENTS_ROOT = os.path.join(PROJECT_ROOT, 'components')

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            # '/home/xfr/workspace/ntuh/fileupload/templates',
            # '/home/xfr/Titanium Studio Workspace/xfr/ntuh/templates',
            # '/home/xfr/workspace/ntuh/templates',
        #    '/home/ntuh/domains/adm.ntuh.net/ntuh/templates',
            os.path.join(BASE_DIR, 'templates').replace('\\','/'),
        ],
        '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',
            ],
             'debug': True,
        },
    },
]


INTERNAL_IPS = (
    # '127.0.0.1',
    '192.168.11.133',
    '192.168.11.175',
    '192.168.10.100',
    '192.168.11.17',
                )

LOGOUT_REDIRECT_URL = '/'

def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

def show_toolbar(request):
    # return not request.is_ajax() and request.user and request.user.username == "xfr"
    return not is_ajax(request=request) and request.user and request.user.username == "xfr"

DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': 'mysite.settings.show_toolbar',
    # Rest of config
}

BOWER_INSTALLED_APPS = (
    'bootstrap',
    'https://github.com/Talv/x-editable.git#develop',
    'fullcalendar',
    # 'jquery',
    # 'underscore',
)

# REST_FRAMEWORK = {
#     'DEFAULT_RENDERER_CLASSES': (
#         'rest_framework.renderers.JSONRenderer',
#         'rest_framework.renderers.BrowsableAPIRenderer',
#         'rest_framework_datatables.renderers.DatatablesRenderer',
#     ),
#     'DEFAULT_FILTER_BACKENDS': (
#         'rest_framework_datatables.filters.DatatablesFilterBackend',
#     ),
#     'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination',
#     'PAGE_SIZE': 50,
# }

CACHEOPS_REDIS = {
    'host': 'localhost', # redis-server is on same machine
    'port': 6379,        # default redis port
    'db': 1,             # SELECT non-default redis database
                         # using separate redis db or redis instance
                         # is highly recommended

    # 'socket_timeout': 3,   # connection timeout in seconds, optional
    # 'password': '...',     # optional
    # 'unix_socket_path': '' # replaces host and port
}

CACHEOPS = {
    'ck.ICD10CMfinal': {
        'ops': 'all', 
        'timeout': 31556926, # 1 year
        'local_get': True,
    },
    # '*.*': {},
}

# CACHEOPS_DEGRADE_ON_FAILURE = True


CELERY_TIMEZONE = "Asia/Taipei"
CELERY_TASK_TRACK_STARTED = True
CELERY_TASK_TIME_LIMIT = 30 * 60

# django-python3-ldap
AUTHENTICATION_BACKENDS=("django_python3_ldap.auth.LDAPBackend",)

# The URL of the LDAP server.
LDAP_AUTH_URL = "ldap://localhost:389"
LDAP_AUTH_URL = "ldap://172.16.3.33:389"


# ldap://172.16.3.33:389/DC=ntuh,DC=gov,DC=tw

# Initiate TLS on connection.
LDAP_AUTH_USE_TLS = False

# The LDAP search base for looking up users.
LDAP_AUTH_SEARCH_BASE = "ou=people,dc=example,dc=com"
LDAP_AUTH_SEARCH_BASE = "DC=ntuh,DC=gov,DC=tw"

# The LDAP class that represents a user.
LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson"
LDAP_AUTH_OBJECT_CLASS = "user"

# User model fields mapped to the LDAP
# attributes that represent them.
LDAP_AUTH_USER_FIELDS = {
    "username": "uid",
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
}
LDAP_AUTH_USER_FIELDS = {
    "username": "sAMAccountName",
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
}

# A tuple of django model fields used to uniquely identify a user.
LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",)

# Path to a callable that takes a dict of {model_field_name: value},
# returning a dict of clean model data.
# Use this to customize how data loaded from LDAP is saved to the User model.
LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data"

# Path to a callable that takes a user model and a dict of {ldap_field_name: [value]},
# and saves any additional user relationships based on the LDAP data.
# Use this to customize how data loaded from LDAP is saved to User model relations.
# For customizing non-related User model fields, use LDAP_AUTH_CLEAN_USER_DATA.
LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations"

# Path to a callable that takes a dict of {ldap_field_name: value},
# returning a list of [ldap_search_filter]. The search filters will then be AND'd
# together when creating the final search filter.
LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters"

# Path to a callable that takes a dict of {model_field_name: value}, and returns
# a string of the username to bind to the LDAP server.
# Use this to support different types of LDAP server.
LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_openldap"
LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory"

# Sets the login domain for Active Directory users.
LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = None

# The LDAP username and password of a user for querying the LDAP database for user
# details. If None, then the authenticated user will be used for querying, and
# the `ldap_sync_users` command will perform an anonymous query.
LDAP_AUTH_CONNECTION_USERNAME = None
LDAP_AUTH_CONNECTION_PASSWORD = None
LDAP_AUTH_CONNECTION_USERNAME = '123456@example.com'
LDAP_AUTH_CONNECTION_PASSWORD = '123456'

# Set connection/receive timeouts (in seconds) on the underlying `ldap3` library.
LDAP_AUTH_CONNECT_TIMEOUT = None
LDAP_AUTH_RECEIVE_TIMEOUT = None

# django-auth-ldap
AUTHENTICATION_BACKENDS = [
    "django_auth_ldap.backend.LDAPBackend",
    "django.contrib.auth.backends.ModelBackend",
]

AUTH_LDAP_SERVER_URI = "ldap://172.16.3.33:389"


import ldap
from django_auth_ldap.config import LDAPSearch

AUTH_LDAP_BIND_DN = "123456@example.com"
AUTH_LDAP_BIND_PASSWORD = "123456"
AUTH_LDAP_USER_SEARCH = LDAPSearch(
    "DC=ntuh,DC=gov,DC=tw", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)"
)

AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0, } 

try:
    from .local_settings import *
except ImportError:
    pass

if 'workspace' in BASE_DIR or 'git' in BASE_DIR:
    DATABASES['default'] = DATABASES['ck_dev']
else:
    DATABASES['default'] = DATABASES['cks']
