# pylint: disable=wrong-import-position
import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.dirname(BASE_DIR) + "/static/"

ALLOWED_ENVIRONMENT_LIST = ['DEV', 'TEST', 'STABLE', 'UAT', 'STAGING', 'LIVEISH', 'LIVE']
ALLOWED_REGION_LIST = ['ID', 'MY', 'PH', 'SG', 'TH', 'TW', 'VN']

ENVIRONMENT = os.getenv('env', 'DEV').upper()
REGION = os.getenv('cid', 'SG').upper()


os.environ['prometheus_multiproc_dir']='/tmp/'

os.getenv('prometheus_multiproc_dir')

# You can create `local_settings.py` in app directory in overwrite REGION and ENVIRONMENT
# Refer to `local_settings_template.py`
try:
	from local_settings import *  # pylint: disable=wildcard-import
except:
	pass

if ENVIRONMENT not in ALLOWED_ENVIRONMENT_LIST or REGION not in ALLOWED_REGION_LIST:
	raise Exception('settings_env_error|env=%s,region=%s' % (ENVIRONMENT, REGION))

DEV = ENVIRONMENT == 'DEV'
TEST = ENVIRONMENT == 'TEST'
STABLE = ENVIRONMENT == 'STABLE'
UAT = ENVIRONMENT == 'UAT'
STAGING = ENVIRONMENT == 'STAGING'
LIVEISH = ENVIRONMENT == 'LIVEISH'
LIVE = ENVIRONMENT == 'LIVE'

if 'LOCALE' not in locals():
	LOCALE = REGION

if 'DEBUG' not in locals():
	DEBUG = DEV or TEST

if 'TEMPLATE_DEBUG' not in locals():
	TEMPLATE_DEBUG = DEBUG

LANGUAGE_CODE = 'en'
TIME_ZONE = 'Asia/Singapore'

from shopeelib.config_manager import init_config, set_config, get_config_table

init_config(
	ENVIRONMENT,
	REGION,
	ALLOWED_ENVIRONMENT_LIST,
	ALLOWED_REGION_LIST
)

# TODO: You can add more configurations here
CACHE_MAIN_INSTANCE_COUNT = None
set_config('CACHE_MAIN_INSTANCE_COUNT', 2)
set_config('CACHE_MAIN_INSTANCE_COUNT', 4, region=['VN', 'ID', 'TW'])
set_config('CACHE_MAIN_INSTANCE_COUNT', 1, env=['DEV', 'TEST', 'STABLE', 'UAT', 'STAGING', 'LIVEISH'])

# This will assign actual values to the above "XXX = None" variables.
# The "XXX = None" statements above is to let IDE behave correctly.
locals().update(get_config_table())

# Disable Django's default logging configure step.
LOGGING_CONFIG = None

LOGGER_CONFIG = {
	'log_dir': os.path.join(os.path.dirname(BASE_DIR), 'log'),
}

ADMINS = ()
MANAGERS = ADMINS

ALLOWED_HOSTS = ["*"]

SITE_ID = 1

# Cookie based cache needed
SECRET_KEY = 'f!y9&hd4xldp)cgxu60d0ut8a4ul^msqbw832-o=%6hs7%&f$*'

USE_I18N = False
USE_L10N = True
USE_TZ = True

APPEND_SLASH = False

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')

INSTALLED_APPS = (
	'django.contrib.auth',
	'django.contrib.contenttypes',
	'django.contrib.sessions',
	'django.contrib.staticfiles',
	'raven.contrib.django.raven_compat',
	'alert_rule_engine',
	'alert_rule_enginelib',
)

MIDDLEWARE_CLASSES = (
	'common.django_utils.ProxyFixMiddleware',
	'django.middleware.common.CommonMiddleware',
	'django.contrib.sessions.middleware.SessionMiddleware',
	#'django.middleware.csrf.CsrfViewMiddleware',
	#'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    # for metrics check
    'common.django_utils.MetricsMiddleware',
    #'alert_rule_engine.stat_middleware.StatsMiddleware'

)

SESSION_COOKIE_NAME = 'session_key'
SESSION_COOKIE_AGE = 3600
SESSION_ENGINE = 'shopeelib.cache_session_engine'
SESSION_CACHE_ALIAS = 'main'
SESSION_COOKIE_SECURE = True
if DEV:
	SESSION_COOKIE_SECURE = False

CSRF_COOKIE_SECURE = True
if DEV:
	CSRF_COOKIE_SECURE = False

STATIC_ROOT = os.path.join(BASE_DIR, '../collectstatic')
STATIC_URL = '/static/'

#if DEV:
#	STATIC_URL = '/static/'

STATICFILES_DIRS = (
	os.path.join(BASE_DIR, '../static').replace('\\', '/'),
)

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

TEMPLATE_LOADERS = (
	('django.template.loaders.cached.Loader', (
		'django.template.loaders.filesystem.Loader',
		'django.template.loaders.app_directories.Loader',
	)),
)

TEMPLATE_DIRS = (
	os.path.join(BASE_DIR, 'template').replace('\\', '/'),
)

ROOT_URLCONF = 'alert_rule_engine.urls'

WSGI_APPLICATION = 'alert_rule_engine.wsgi.application'

GEOIP_PATH = '/usr/share/GeoIP/'

DATABASE_ROUTERS = ['common.django_model.DatabaseRouter',]

# TODO: Update the DB configurations
DATABASES = {
	'default': {
		'ENGINE': 'django.db.backends.mysql',
		'NAME': 'alert_rule_engine_%s_db' % REGION.lower(),
		'USER': 'shopee_dev_all',
        'PASSWORD': 'jdoriqejrov$#)EV0VJR',
        'HOST': "10.65.145.7",
        'PORT': '50028',
		'CONN_MAX_AGE': 3600,
		'OPTIONS': {'charset': 'utf8mb4'},
	},
	'alert_rule_engine_sg_db.write': {
		'ENGINE': 'django.db.backends.mysql',
		'NAME': 'alert_rule_engine_%s_db' % REGION.lower(),
		'USER': 'shopee_dev_all',
        'PASSWORD': 'jdoriqejrov$#)EV0VJR',
        'HOST': "10.65.145.7",
        'PORT': '50028',
		'CONN_MAX_AGE': 3600,
		'OPTIONS': {'charset': 'utf8mb4'},
	},
	'alert_rule_engine_sg_db.read': {
		'ENGINE': 'django.db.backends.mysql',
		'NAME': 'alert_rule_engine_%s_db' % REGION.lower(),
		'USER': 'shopee_dev_all',
        'PASSWORD': 'jdoriqejrov$#)EV0VJR',
        'HOST': "10.65.145.7",
        'PORT': '50028',
		'CONN_MAX_AGE': 3600,
		'OPTIONS': {'charset': 'utf8mb4'},
	},
}

if DEV:
    for key in DATABASES:
        db = DATABASES[key]
#        db['NAME'] = 'alert_rule_engine_%s_db' % REGION.lower()
#        db['USER'] = 'shopee_dev_all'
#        db['PASSWORD'] = 'jdoriqejrov$#)EV0VJR'
#        db['HOST'] = '203.116.180.207'
#        db['PORT'] = '45003'
        db['NAME'] = 'alert_rule_engine_%s_db' % REGION.lower()
        db['USER'] = 'readmin'
        db['PASSWORD'] = 'zabbix2018'
        db['HOST'] = '127.0.0.1'
        db['PORT'] = '3306'
#print (DATABASES)

if UAT or STAGING:
	for key in DATABASES:
		db = DATABASES[key]
		db['USER'] = ''
		db['PASSWORD'] = ''
		db['HOST'] = ''

# TODO: Update cache configurations
CACHE_SERVICE_NAME = 'alert_rule_engine-redis-%s-%s' % (ENVIRONMENT.lower(), REGION.lower())

DEFAULT_SERVICE_DEPENDENCIES = {
	CACHE_SERVICE_NAME: ['127.0.0.1:6379'],
}

from shopeelib.service_dependency_manager import ServiceDependencyManager
SERVICE_DEPENDENCY_MANAGER = ServiceDependencyManager(
	os.path.join(os.path.dirname(BASE_DIR), 'service_deps', 'services.json'),
	DEFAULT_SERVICE_DEPENDENCIES)

COMMON_CACHES = {
	'main': {
		'default': True,
		'type': 'dynamic_distribution',
		'name_pattern': 'main.%d',
		'service_name': CACHE_SERVICE_NAME,
		'service_dependency_manager': SERVICE_DEPENDENCY_MANAGER,
		'client_config': {
			'type': 'redis',
			'default_timeout': 7 * 24 * 60 * 60,
			'key_prefix': 'alert_rule_engine.'
		},
	}
}

#if DEV:
#	COMMON_CACHES = {
#		'main': {
#			'default': True,
#			'type': 'memory',
#		}
#	}
#
# my template file:
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request")

#IMAGE_ROOT = os.path.join(BASE_DIR, 'media')
