"""
Django settings for lm project.

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

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

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

import os
import json
import socket
from boto3.session import Session


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

SCRAPYD_IP = None

SECRETS = None
secrets_path = "/run/secrets/secrets"
if os.path.exists(secrets_path):
    SECRETS = json.loads(open(secrets_path).read())

if "DEV" in os.environ:
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
    SECRET_KEY = 'kw!3bqy4e39x0@xhoor4uvpwj!hgofxh9p5=j7^9$x-i*41vc_'
    DEBUG = True

    if 'CMS' in os.environ:
        SECRET_KEY = 'wdh|w>q&&roC*UEF-&~fNHwM,~GaUH2tC6Pn+)F2=GSQ*8DaM]'
        CMS_TEMP_SUPER_USERNAME = "admin"
        CMS_TEMP_SUPER_PASSWORD = "password"
        SCRAPYD_API_KEY = "scrapydapikey"
        SCRAPYD_IP = socket.gethostbyname("scrapyd_dev")
        SESSION_COOKIE_NAME = "cms_sessionid_dev"
else:
    # Settings for production
    DEBUG = False

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = SECRETS["django_secret"]

    if 'CMS' in os.environ:
        SECRET_KEY = SECRETS["django_secret"]
        CMS_TEMP_SUPER_USERNAME = "admin"
        CMS_TEMP_SUPER_PASSWORD = SECRETS["cms_admin_pwd"]
        SCRAPYD_API_KEY = SECRETS["scrapyd_api_key"]
        SCRAPYD_IP = socket.gethostbyname("scrapyd")
        SESSION_COOKIE_NAME = "cms_sessionid"

    assert(not DEBUG)

print("Debug set to", str(DEBUG))

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

# Redirect here after /login
LOGIN_REDIRECT_URL = '/'

if "CMS" in os.environ:
    LOGIN_REDIRECT_URL = '/cms'

ALLOWED_HOSTS = ["*"]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.postgres',
    'app',
]

if "CMS" in os.environ:
    INSTALLED_APPS.append("cms")


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',
    'htmlmin.middleware.HtmlMinifyMiddleware',
    'htmlmin.middleware.MarkRequestMiddleware',
]

QUERYCOUNT = {
    "IGNORE_REQUEST_PATTERNS": ["^/favicon.ico"]
}

# if DEBUG:
    # MIDDLEWARE.append("querycount.middleware.QueryCountMiddleware")

ROOT_URLCONF = 'lm.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
                'app.context_processors.export_vars',
            ],
        },
    },
]

if "CMS" in os.environ:
    cms_context_proc = "cms.context_processors.export_vars"
    TEMPLATES[0]["OPTIONS"]["context_processors"].append(cms_context_proc)

WSGI_APPLICATION = 'lm.wsgi.application'

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

DATABASE_ROUTERS = []
if "CMS" in os.environ:
    DATABASE_ROUTERS.append("cms.db_routers.CmsRouter")

DATABASES = None

if "DEV" in os.environ:
    if "CMS" in os.environ:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.postgresql',
                'NAME': 'admin',
                'USER': 'postgres',
                'PASSWORD': os.environ['DB_PWD'],
                'HOST': 'admin_db_dev',
                'PORT': '5432',
            },
            'app_server': {
                'ENGINE': 'django.db.backends.postgresql',
                'NAME': 'liftedmobile',
                'USER': 'postgres',
                'PASSWORD': os.environ['LM_DB_PWD'],
                'HOST': os.environ['LM_DB_HOSTNAME'],
                'PORT': '5432',
            }
        }
    else:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.postgresql',
                'NAME': 'liftedmobile',
                'USER': 'postgres',
                'PASSWORD': os.environ['DB_PWD'],
                'HOST': 'liftedmobile_db_dev',
                'PORT': '5432',
            }
        }
else:
    DATABASES = SECRETS["db_config"]


# Password hashing
# https://docs.djangoproject.com/en/1.11/topics/auth/passwords/#using-argon2-with-django

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
]

# Password validation
# https://docs.djangoproject.com/en/1.11/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.11/topics/i18n/

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

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

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

LOGGING = None
if not DEBUG:
    aws_cw = SECRETS["cloudwatch_config"]

    boto3_session = Session(aws_access_key_id=aws_cw["access_key_id"],
                            aws_secret_access_key=aws_cw["secret_access_key"],
                            region_name=aws_cw["region_name"])

    stream_name = "lm_django_debug"
    if "CMS" in os.environ:
        stream_name = "cms_django_debug"

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'file': {
                'level': 'DEBUG',
                'class': 'logging.FileHandler',
                'filename': '/var/log/django/debug.log'
            },
            'watchtower':  {
                'level': 'DEBUG',
                'class': 'watchtower.CloudWatchLogHandler',
                'boto3_session': boto3_session,
                'log_group': 'liftedmobile_logs',
                'stream_name': stream_name
            },
        },
        'loggers': {
            'django': {
                'handlers': ['file', 'watchtower'],
                'level': 'DEBUG',
                'propagate': True,
            },
        },
    }
