"""
Django settings for stagecraft project.

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

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

import json
import sys
from os.path import abspath, dirname, join as pjoin

from .rediss import *

try:
    from urllib.parse import urlparse  # Python 3
except ImportError:
    from urlparse import urlparse  # Python 2

BASE_DIR = abspath(pjoin(dirname(__file__), '..', '..'))

sys.path.append(pjoin(BASE_DIR, 'apps'))
sys.path.append(pjoin(BASE_DIR, 'libs'))

import djcelery
from celery.schedules import crontab

djcelery.setup_loader()

# Defined here for safety, they should also be defined in each environment.
DEBUG = False

ALLOWED_HOSTS = []

USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

STATSD_HOST = 'localhost'
STATSD_PORT = 8125
STATSD_PREFIX = 'pp.apps.stagecraft'
STATSD_MAXUDPSIZE = 512
STATSD_CLIENT = 'django_statsd.clients.normal'


def load_paas_settings():
    paas = {}
    if 'VCAP_SERVICES' in os.environ:
        vcap = json.loads(os.environ['VCAP_SERVICES'])
        for service in vcap['postgres']:
            if service['name'] == 'gds-performance-platform-pg-service':
                paas['DATABASE_URL'] = service['credentials']['uri']
        for service in vcap['redis']:
            if service['name'] == 'redis':
                database_number = os.environ['REDIS_DATABASE_NUMBER']
                url = service['credentials']['uri']
                url += '/' + database_number
                paas['REDIS_URL'] = url
    return paas


def load_databases_from_environment():
    # eg postgres://user3123:pass123@database.foo.com:6212/db982398
    DATABASE_URL = urlparse(os.environ['DATABASE_URL'])
    return {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': DATABASE_URL.path[1:],
            'USER': DATABASE_URL.username,
            'PASSWORD': DATABASE_URL.password,
            'HOST': DATABASE_URL.hostname,
            'PORT': DATABASE_URL.port,
        }
    }


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',