
import ldap
import strictyaml
import purist.limitmonitor

from decouple import Config, Csv, RepositoryIni
from django_auth_ldap.config import LDAPSearch

from .settings_original import *

#
# LOAD CONFIGURATION FILE
#

CONFIG_PATH = '/etc/opt/purist/middleware/config.ini'
SECRET_PATH = '/etc/opt/purist/middleware/secret.ini'
LINK_PROFILE_PATH = '/etc/opt/purist/middleware/link_profile.strict.yml'

config = Config(RepositoryIni(CONFIG_PATH))
secret_config = Config(RepositoryIni(SECRET_PATH))

with open(LINK_PROFILE_PATH, 'r') as stream:
    LINK_PROFILE_ORDERED_DICT = strictyaml.load(stream.read()).data

#
# SECURITY
#

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = secret_config("DJANGO_SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config("DEBUG", cast=bool)

# it is safe to use these flags in production
DEBUG_ALL_ACCESS = config("DEBUG_ALL_ACCESS", cast=bool)
DEBUG_CHANGE_PASSWORD = config("DEBUG_CHANGE_PASSWORD", cast=bool)
DEBUG_SKIP_ACTIVATION_COMMAND = config("DEBUG_SKIP_ACTIVATION_COMMAND", cast=bool)
DEBUG_SKIP_VALIDATE_ON_AUTHENTICATION = config("DEBUG_SKIP_VALIDATE_ON_AUTHENTICATION", cast=bool)
DEBUG_REGISTER_STATUS = config("DEBUG_REGISTER_STATUS", cast=bool)
DEBUG_REMOVE_CAPTCHA = config("DEBUG_REMOVE_CAPTCHA", cast=bool)



# Required if DEBUG is False
ALLOWED_HOSTS = config("ALLOWED_HOSTS", cast=Csv())

#
# INSTALLED APPLICATIONS
#

INSTALLED_APPS += ["crispy_forms",
                   "django_agpl",
                   "django_celery_beat",
                   "django_extensions",
                   "ldapregister",
                   "limitmonitor",
                   "purist",
                   "captcha",
                   "cart",
                   "registration",
                   "rest_framework",
                   "password_reset",
                   "invitation",
                   "bundlechange"]

#
# AGPL APPLICATION
#

AGPL_ROOT = os.path.abspath(os.path.dirname(__file__) + "/..")

# no special exclusions are required, configuration and secrets are not stored in the site folder
# cross-check with .gitignore

AGPL_EXCLUDE_DIRS = [
    r'^CVS$',
    r'^site_media$',
    r'^uploads$',
    r'\.git$',
    r'\.svn$',
    r'\.idea$',
    r'\.kdev4$',
    r'\scripts$',
]

AGPL_EXCLUDE_FILES = [
    r'^site_settings.py$',
    r'^local_settings.py$',
    r'^\.gitignore$',
    r'\.pyc$',
    r'\.sql$',
    r'\.sqlite$',
	r'^categories.json$',
	r'^confusables.json$',
]

AGPL_FILENAME_PREFIX = 'middleware'

#
# REGISTRATION APPLICATION
#

REGISTRATION_OPEN = config("REGISTRATION_OPEN", cast=bool)

REG_PERSON_BASE_DN = config("REG_PERSON_BASE_DN")
REG_PERSON_OBJECT_CLASSES = config("REG_PERSON_OBJECT_CLASSES", cast=Csv())

REG_GROUP_BASE_DN = config("REG_GROUP_BASE_DN")
REG_GROUP_OBJECT_CLASSES = config("REG_GROUP_OBJECT_CLASSES", cast=Csv())
REG_BAD_SUBSTRINGS = config.get("REG_BAD_SUBSTRINGS", cast=Csv(str))

#
#  AUTHENTICATION
#

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'purist.custom.PassphraseValidator',
    },
]

AUTHENTICATION_BACKENDS = (
    'purist.custom.AuthenticationBackend',
)

AUTH_LDAP_SERVER_URI = config("AUTH_LDAP_SERVER_URI")
AUTH_LDAP_START_TLS = config("AUTH_LDAP_START_TLS", cast=bool)

AUTH_LDAP_BIND_DN = config("AUTH_LDAP_BIND_DN")
AUTH_LDAP_BIND_PASSWORD = secret_config("AUTH_LDAP_BIND_PASSWORD")

BASE_DN = config("AUTH_LDAP_USER_SEARCH_BASE_DN")
AUTH_LDAP_USER_SEARCH = LDAPSearch(BASE_DN, ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
# must match `base_dn` and primary key in `ldapregister.models.LdapPerson`

AUTH_USER_MODEL = 'purist.User'

#
# DATABASE
#

# See also:
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
# and https://pypi.python.org/pypi/django-ldapdb/
# (re-uses LDAP connection details from authentication settings)

SQLITE_DB_PATH = config("SQLITE_DB_PATH")

PSQL_DB_NAME = secret_config('PSQL_DB_NAME')
PSQL_USER_NAME = secret_config('PSQL_USER_NAME')
PSQL_USER_PASSWORD = secret_config('PSQL_USER_PASSWORD')
PSQL_HOST = secret_config('PSQL_HOST')
PSQL_PORT = secret_config('PSQL_PORT')

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': PSQL_DB_NAME,
        'USER': PSQL_USER_NAME,
        'PASSWORD': PSQL_USER_PASSWORD,
        'HOST': PSQL_HOST,
        'PORT': PSQL_PORT,
    },
    'ldap': {
        'ENGINE': 'ldapdb.backends.ldap',
        'NAME': AUTH_LDAP_SERVER_URI,
        'USER': AUTH_LDAP_BIND_DN,
        'PASSWORD': AUTH_LDAP_BIND_PASSWORD,
        'TLS': AUTH_LDAP_START_TLS,
    },
}

DATABASE_ROUTERS = ['ldapdb.router.Router']

#
# Context processor that makes the django settings avaiable to templates
#

TEMPLATES[0]['OPTIONS']['context_processors'].append('purist.context_processors.settings')
TEMPLATES[1]['OPTIONS']['context_processors'] = ['purist.context_processors.settings']


#
# STATIC AND SITE SETTINGS
#

STATIC_ROOT = config("STATIC_ROOT")
STATICFILES_DIRS = config("STATICFILES_DIRS", cast=Csv())
SITE_TITLE = config("SITE_TITLE")
SITE_BYLINE = config("SITE_BYLINE")
SITE_DOMAIN = config("SITE_DOMAIN")
SITE_PROVIDER = config("SITE_PROVIDER")
SITE_PROVIDER_LINK = config("SITE_PROVIDER_LINK")

#
# WOOCOMMERCE
#

WOO_URL = config("WOO_URL")
WOO_WP_API = config("WOO_WP_API", cast=bool)
WOO_VERSION = config("WOO_VERSION")
WOO_QUERY_STRING_AUTH = config("WOO_QUERY_STRING_AUTH", cast=bool)  # required for OAuth over HTTPS
WOO_CONSUMER_KEY = secret_config("WOO_CONSUMER_KEY")
WOO_CONSUMER_SECRET = secret_config("WOO_CONSUMER_SECRET")
WOO_API_TIMEOUT = config("WOO_API_TIMEOUT", 5, cast=int)

#
# WOOCOMMERCE CART
#

WOO_CART_BILLING_PATH = config("WOO_CART_BILLING_PATH")
WOO_CART_THANKS_PATH = config("WOO_CART_THANKS_PATH")
WOO_REG_OPTIONS_INFO_FILE = config(
    "WOO_REG_OPTIONS_INFO_FILE",
    default='/etc/opt/purist/middleware/registration_options.yml'
)

#
# WOOSUB1 PARSER
#

WOOSUB1_PRODUCT_LIST = config("WOOSUB1_PRODUCT_LIST", cast=Csv(int))
WOO_PARENT_PROD_ID = config("WOO_PARENT_PROD_ID")
WOO_UPGRADE_PAY_URL = config("WOO_UPGRADE_PAY_URL")
WOO_BUNDLES_INFO_FILE = config(
    "WOO_BUNDLES_INFO_FILE",
    default='/etc/opt/purist/middleware/upgrades_downgrades.yml'
)

#
# LIMIT MONITOR
#

LM_SERVICES = purist.limitmonitor.ServicesContainer
LM_PARSERS = purist.limitmonitor.ParserContainer

#
# LOGGING
#

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': None,
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        '': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}


#
# Captcha
#

CAPTCHA_FONT_SIZE = 40
CAPTCHA_TIMEOUT = 15
CAPTCHA_LENGTH = 4
CAPTCHA_TEST_MODE = True
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
CAPTCHA_LETTER_ROTATION = (0,5)
CAPTCHA_MATH_CHALLENGE_OPERATOR = 'x'
CAPTCHA_NOISE_FUNCTIONS = ()
CAPTCHA_FONT_SIZE = 19

#
# Tunnel
#

TUNNEL_IDENTITY = secret_config('TUNNEL_IDENTITY')
TUNNEL_SECRET = secret_config('TUNNEL_SECRET')
TUNNEL_HOST = config('TUNNEL_HOST')
TUNNEL_KEY = secret_config('TUNNEL_KEY')

#
# REST framework
#

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS':
    'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}


#
# django password recover: 30 min
#
PASSWORD_RESET_TOKEN_EXPIRES = secret_config('PASSWORD_RESET_TOKEN_EXPIRES', 1800)

# Email server configuration
ADMINS = config(
    'ADMINS_EMAIL',
    cast=lambda v: [tuple(
        j.strip() for j in s.split(',')) for s in v.split(';')])
DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL',
                            'Change me <noreply@example.com>')
SERVER_EMAIL = config('SERVER_EMAIL',
                      'Change me <noreply@example.com>')
EMAIL_BACKEND = config('EMAIL_BACKEND','django.core.mail.backends.smtp.EmailBackend')
EMAIL_HOST = config('EMAIL_HOST', 'localhost')
EMAIL_HOST_USER = config('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = secret_config('EMAIL_HOST_PASSWORD', '')
EMAIL_PORT = config('EMAIL_PORT', 25, cast=int)
EMAIL_USE_TLS = config('EMAIL_USE_TLS', False, cast=bool)
EMAIL_USE_SSL = config('EMAIL_USE_SSL', False, cast=bool)

# This is the link to the subscribe page, used in different parts of the middleware
SUBSCRIBE_HREF = config('SUBSCRIBE_HREF')
