"""
Django settings for example project.

Generated by Cookiecutter Django Package

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

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

import os
import sys

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "oooooooooooooooooooooooooooooooooooooooooooooooooo"

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

ALLOWED_HOSTS = []
USE_DJANGO_RQ = True

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #'django_task.apps.DjangoTaskConfig',
    'django_task',
    'example',
    'tasks',
]

if USE_DJANGO_RQ:
    INSTALLED_APPS += [
        'django_rq',
    ]


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'example.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'example.wsgi.application'

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

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

DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    # {
    #     'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    # },
    # {
    #     'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    # },
    # {
    #     'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    # },
    # {
    #     'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    # },
]

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

LANGUAGE_CODE = 'en-us'

#TIME_ZONE = 'UTC'
TIME_ZONE = 'Europe/Rome'

USE_I18N = True

USE_L10N = True

USE_TZ = True

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

STATIC_URL = '/static/'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

################################################################################
#   Echo helpers

def settings_echo(message, title='', error=False, warning=False):
    """
    Helpers to display a message
    """
    # Avoid echoing twice when executing runserver
    if os.environ.get('RUN_MAIN') is None:
        if error:
            prefix = "\x1b[41;37m"
        elif warning:
            prefix = "\x1b[43;30m"
        else:
            prefix = "\x1b[47;30m"
        suffix = " \x1b[0m"
        if title:
            print(prefix + str(title) + ':' + suffix, file=sys.stderr, end ="")
        print(prefix + str(message) + suffix, file=sys.stderr,)


################################################################################
#   Constants

INSTANCE_PREFIX = "example"
try:
    from example.settings.instance_prefix import *
except Exception as e:
    #print('ERROR: %s' % str(e))
    #settings_echo(str(e), title='WARNING', error=False, warning=True)
    pass

SESSION_COOKIE_NAME = INSTANCE_PREFIX + '_sid'

settings_echo(INSTANCE_PREFIX, title='INSTANCE_PREFIX')
settings_echo(SESSION_COOKIE_NAME, title='SESSION_COOKIE_NAME')

#
# Redis config
#

#REDIS_URL = 'redis://localhost:6379/0'
redis_host = os.environ.get('REDIS_HOST', 'localhost')
redis_port = 6379
REDIS_URL = 'redis://%s:%d/0' % (redis_host, redis_port)
settings_echo(REDIS_URL, title='REDIS_URL')

# CACHES = {
#     'default': {
#         'BACKEND': 'redis_cache.RedisCache',
#         'LOCATION': REDIS_URL
#     },
# }

# SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'

#
# RQ config
#

RQ_SHOW_ADMIN_LINK = False
DJANGOTASK_LOG_ROOT = os.path.abspath(os.path.join(BASE_DIR, '..', 'protected', 'tasklog'))
DJANGOTASK_ALWAYS_EAGER = False
DJANGOTASK_JOB_TRACE_ENABLED = False
DJANGOTASK_REJECT_IF_NO_WORKER_ACTIVE_FOR_QUEUE = True

QUEUE_DEFAULT = INSTANCE_PREFIX + '_default'
QUEUE_LOW = INSTANCE_PREFIX + '_low'
QUEUE_HIGH = INSTANCE_PREFIX + '_high'

RQ_QUEUES = {
    QUEUE_DEFAULT: {
        'URL': REDIS_URL,
        #'PASSWORD': 'some-password',
        #'DEFAULT_TIMEOUT': 5 * 60,
        'DEFAULT_TIMEOUT': -1,  # -1 means infinite
    },
    QUEUE_LOW: {
        'URL': REDIS_URL,
        #'ASYNC': False,
        'DEFAULT_TIMEOUT': 10 * 60,
    },
    QUEUE_HIGH: {
        'URL': REDIS_URL,
        'DEFAULT_TIMEOUT': 500,
    },
}

settings_echo('', title='RQ_QUEUES')
for rq_queue_key, rq_queue_value in RQ_QUEUES.items():
    settings_echo(rq_queue_value, title='- ' + rq_queue_key)
