"""
Django settings for elopsys project.

Generated by 'django-admin startproject' using Django 1.10.3.

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
from __future__ import absolute_import
import os
import git

import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
path = lambda *a: os.path.join(BASE_DIR, *a)


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

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

REVISION = git.Repo(PROJECT_ROOT).head.commit.hexsha


LOG_FOLDER=os.path.join(PROJECT_HOME, '..', 'logs')

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', '+%j&^4=$a6w3m3s1(*z9y-eey--o%owq2au-3kdz)c2)jdj52q')

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

ALLOWED_HOSTS = ['*']

EMAIL_HOST = 'smtp.office365.com'
EMAIL_HOST_USER = 'help@emeraldlife.co.za'
EMAIL_HOST_PASSWORD = 'Zoqo6640'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
SEND_COMMS = True

#CLICKATEL SMS Settings
CLICKATEL_USERNAME = "emerald"
CLICKATEL_PASSWORD = "Upw2RD"
CLICKATEL_API_ID = 3594583
CLICKATEL_API_URL = "https://api.clickatell.com/http/sendmsg"

SMS_TEST_MODE = False

#Cellery Config
CELERY_RESULT_BACKEND='djcelery.backends.database.DatabaseBackend'
USE_CELERY = True

AUTH_USER_MODEL = "operations.OperationsUser"
# Application definition

EL_PAGINATION_PER_PAGE=15
EL_PAGINATION_ADD_NOFOLLOW=True

EMERALD_API_USER = 'elipsys_api_user'

INSTALLED_APPS = [

    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    # Django Autocomplete Lite Apps
    'dal',
    'dal_select2',
    # 'dal_queryset_sequence',

    'django.contrib.admin',
    'rest_framework',
    'rest_framework.authtoken',
    'bootstrap4',
    'django_js_reverse',
    'simple_history',
    'el_pagination',
    'operations',
    'fleet_management',
    'it_support',
    'employees',
    'api',
    # 'facilities',
    'assets',
    'djcelery',

]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

MIDDLEWARE_CLASSES = [
    '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',
    'simple_history.middleware.HistoryRequestMiddleware',

]

ROOT_URLCONF = 'operations.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',
            ],
        },
    },
]


BROKER_URL = os.environ.get('BROKER_URL', 'amqp://guest:guest@localhost//')
CELERY_RESULT_BACKEND ='djcelery.backends.database.DatabaseBackend'
USE_CELERY = True #os.environ.get('CELERY_INSTEAD_OF_THREADS', 'False') == 'True'

# make sure SMS_TEST_MODE is TRUE for non-prod environments
# defined in vars file for environment

from celery.schedules import crontab

CELERYBEAT_SCHEDULE = {
#     # 'birthday_sms': {
#     #     'task': '',
#     #     'schedule': crontab(hour=9, minute=0),
#     # },
#     # 'dependent_cover_sms': {
#     #     'task': '',
#     #     'schedule': crontab(hour=9, minute=30),

#     # },
#     # 'no_submissions_sms': {
#     #     'task': '',
#     #     'schedule': crontab(hour=10, minute=0),
#     # },
#     # 'submit_to_stratcol': {
#     #     'task': '',
#     #     'schedule': crontab(minute='*/30'),
#     # }
}

WSGI_APPLICATION = 'operations.wsgi.application'


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

import dj_database_url
DATABASES = {
    'default': dj_database_url.config(default='sqlite:///{0}'.format(path('db.sqlite3')))
}



# Password validation
# https://docs.djangoproject.com/en/1.10/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',
    },
]


LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(message)s'
            },
        'simple': {
            'format': '%(asctime)s %(levelname)s %(message)s'
            },
        },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
            },
        'file':{
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename':os.path.join(LOG_FOLDER, 'operations.log'),
            'formatter': 'verbose',
            'maxBytes':604800,
            'backupCount':50
            }
        },
    'loggers': {
        'django': {
            'handlers':['mail_admins',],
            'propagate': True,
            'level':'DEBUG',
            },
        '': {
            'handlers': ['file',],
            'propagate': True,
            'level': 'DEBUG'
            }
        },
    }


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

DATE_INPUT_FORMATS = ('%Y-%m-%d')

TIME_ZONE = 'Africa/Johannesburg'


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

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "statics"),
#         #'/var/www/static/',
)

STATIC_URL = '/static/'+REVISION+'/'
# STATIC_ROOT = os.path.join(PROJECT_HOME, '..', 'statics_collected', REVISION)
STATIC_ROOT = os.path.join('/var/static', REVISION)

MEDIA_URL= '/media/'
#MEDIA_ROOT = os.path.join(PROJECT_HOME, '..', 'media')
MEDIA_ROOT = '/var/media'

CRISPY_TEMPLATE_PACK = "bootstrap3"

if os.path.exists(os.path.join(PROJECT_HOME, "operations", "local_settings.py")):
    from operations.local_settings import *

#check that required settings are set
if DATABASES['default']['ENGINE'] == 'django.db.backends.':
    raise Exception("Unconfigured databases setting, please correct in local_settings.py")

DATABASES['default']['ATOMIC_REQUESTS'] = True

BASE_URL = 'https://ops.elipsysglobal.co.za'

SERVICE_CHECK = 1500

#################
#
# DON'T PUT ANY MORE SETTINGS AFTER THIS POINT, OTHERWISE local_settings.py CAN'T OVERRIDE THEM
#
#




