# Django settings for pbp_com project.
import os
import sys
import logging

logger = logging.getLogger(__name__)

# Directories
SRC_ROOT = os.path.dirname(os.path.realpath(os.path.dirname(__file__)))
BASE_DIR = os.path.join(SRC_ROOT, 'pbp_com')
sys.path.append(BASE_DIR)

STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "https://penobscotbaypress.com/static/"

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
if os.getenv('DJANGO_USE_PUBLIC_MEDIA', False):
    logger.debug('Using media content from the production website!')
    MEDIA_URL = "https://penobscotbaypress.com" + MEDIA_URL

# MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = STATIC_URL + "admin/"
TEMPLATE_DIRS = os.path.join(BASE_DIR, "templates")

DEBUG = os.getenv("DJANGO_DEBUG", False)
TEMPLATE_DEBUG = DEBUG

SITE = os.getenv("DJANGO_SITE", "PBP")
if SITE == "PBP":
    SITE_ID = 2
if SITE == "WP":
    SITE_ID = 3
if SITE == "IA":
    SITE_ID = 4
if SITE == "CP":
    SITE_ID = 5

site_log_msg = 'Running content and URLs from site %s'
logger.debug(site_log_msg.format(SITE))

ROOT_URLCONF = "pbp_com.urls"
if SITE != "PBP":
    ROOT_URLCONF = "pbp_com.paper_urls"

# Django settings for pbp project.
ADMINS = ("Jeremiah Savage", "jeremiahs@pbp.me")

STOREFRONT_HELP_TO = ["subscriptions@pbp.me", "web@pbp.me"]
# change of address email
NOTIFICATIONS_EMAIL = ["subscriptions@pbp.me", "web@pbp.me"]

LANGUAGE_CODE = "en-us"
MANAGERS = ADMINS
USE_I18N = True
APPEND_SLASH = False
SMART_APPEND_SLASH = True
SEND_BROKEN_LINK_EMAILS = False
IGNORABLE_404_STARTS = (
    "/vault/loginout.html",
    "/calendar/submitanevent.html",
    "robots.txt",
)
# Used to exclude adzone clicks from PBP offices
INTERNAL_IPS = (
    "24.93.128.34",
    "70.16.110.194",
)

TIME_ZONE = "America/New_York"
LANGUAGE_CODE = "en-us"

AUTH_PROFILE_MODULE = "profiles.UserProfile"

LOGIN_REDIRECT_URL = "/store/"

CACHE_MIDDLEWARE_SECONDS = 10

if os.getenv("DJANGO_CACHE_ENABLED", True):
    CACHES = {
        "default": {
            "BACKEND": "django.core.cache.backends.memcached.MemcachedCache",
            "LOCATION": "127.0.0.1:11211",
        }
    }
    CACHE_MIDDLEWARE_ALIAS = "default"
    CACHE_MIDDLEWARE_SECONDS = 8600
    CACHE_MIDDLEWARE_KEY_PREFIX = os.getenv("DJANGO_CACHE_PREFIX", "pbp_")

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "NAME": os.getenv("DJANGO_DB_NAME", "pbp"),
        "USER": os.getenv("DJANGO_DB_USER", "pbp"),
        "PASSWORD": os.getenv("DJANGO_DB_PASS", ""),
        "HOST": os.getenv("DJANGO_DB_HOST", "localhost"),
        "PORT": os.getenv("DJANGO_DB_PORT", ""),
    }
}

INTERNAL_IPS = (
    "24.93.128.34",
    "70.16.110.194",
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
)

SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "notasecret20934kljsdf")

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",
    "pbp_core.context_processors.pbp_store",
    "adzone.context_processors.get_source_ip",
)

MIDDLEWARE_CLASSES = (
    "django.middleware.cache.UpdateCacheMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "pbp_com.middleware.CurrentSiteMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "ipfilter.middleware.FilterIPs",
    "pbp_com.middleware.SmartAppendSlashMiddleware",
    "pbp_com.middleware.SetRemoteAddrMiddleware",
    "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.contrib.redirects.middleware.RedirectFallbackMiddleware",
    "django.middleware.cache.FetchFromCacheMiddleware",
)

AUTHENTICATION_BACKENDS = ("django.contrib.auth.backends.ModelBackend",)

ROOT_URLCONF = "pbp_com.urls"

# Django Merchant settings
MERCHANT_TEST_MODE = True
MERCHANT_SETTINGS = None  # needs to set explicitly

# if SITE_ID == PBP:
HAYSTACK_SITECONF = "pbp_com.search_sites"
HAYSTACK_SEARCH_ENGINE = "whoosh"
HAYSTACK_WHOOSH_PATH = os.path.join(BASE_DIR, "search-index")
CLASSIFIED_LENGTH = 200
INSTALLED_APPS = (
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.redirects",
    "django.contrib.staticfiles",
    "django.contrib.admin",
    "django.contrib.markup",
    "django.contrib.humanize",
    "django.contrib.comments",
    "django.contrib.admindocs",
    "django.contrib.sitemaps",
    "django.contrib.flatpages",
    "django_extensions",
    "registration",
    "profiles",
    "debug_toolbar",
    "typogrify",
    "taggit",
    "markitup",
    "django_inlines",
    "convert",
    "ipfilter",
    "documents",
    "newsroom",
    "darkroom",
    "adzone",
    "directory",
    "marketplace",
    "remember",
    "classifieds",
    "historical",
    "almanac",
    "visitors",
    "haystack",
)

PASSWORD_HASHERS = (
    "django.contrib.auth.hashers.PBKDF2PasswordHasher",
    "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
    "django.contrib.auth.hashers.BCryptPasswordHasher",
    "django.contrib.auth.hashers.SHA1PasswordHasher",
    "django.contrib.auth.hashers.MD5PasswordHasher",
    "django.contrib.auth.hashers.CryptPasswordHasher",
)

# API key is for penobscotbaypress.com
GOOGLE_API_KEY = os.getenv(
    "GOOGLE_API_KEY",
    "ABQIAAAATux_aKmAEX7DnojAr8SqlRTyl9CS5q3L9FIn7JSvfaKvyESzUhR20N-9Pqstiw45F-wXH6msAoVaKw"
)

##### For Email ########
ACCOUNT_ACTIVATION_DAYS = 15
# EMAIL_HOST="smtp.3ip.net"
# EMAIL_HOST_USER="cpowell@penobscotbaypress.com"
# EMAIL_HOST_PASSWORD="cpow07"
# DEFAULT_FROM_EMAIL="cpowell@penobscotbaypress.com"
# EMAIL_USE_TLS = True
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "secure.emailsrvr.com"
EMAIL_HOST_USER = "orders@pbp.me"
EMAIL_HOST_PASSWORD = "P3Pp@ss"
DEFAULT_FROM_EMAIL = "orders@pbp.me"
EMAIL_USE_TLS = True

LOG_LEVEL = os.getenv('DJANGO_LOG_LEVEL', 'INFO')
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'root': {'handlers': [], 'level': 'ERROR',},
    'filters': {},
    'formatters': {
        # black red green yellow blue purple cyan white
        # {color}, fg_{color}, bg_{color}: Foreground and background colors.
        # bold, bold_{color}, fg_bold_{color}, bg_bold_{color}: Bold/bright colors.
        # thin, thin_{color}, fg_thin_{color}: Thin colors (terminal dependent).
        'color': {
            '()': 'colorlog.ColoredFormatter',
            'format': "{log_color}{levelname:8s}{reset} {thin_white}{message}",
            'style': '{',
        },
        'color-verbose': {
            '()': 'colorlog.ColoredFormatter',
            # \r returns caret to line beginning, in tests this eats the silly dot that removes
            # the beautiful alignment produced below
            'format': '\r'
            '{log_color}{levelname:8s}{reset} '
            '{bold_cyan}{name}{reset}:'
            '{fg_bold_red}{lineno}{reset} '
            '{thin_yellow}{funcName} '
            '{thin_white}{message}'
            '{reset}',
            'style': '{',
        },
        'sqlformatter': {'()': 'sqlformatter.SqlFormatter', 'format': '%(levelname)s %(message)s',},
    },
    'handlers': {
        'no-color': {'class': 'logging.StreamHandler', 'filters': []},
        'color': {'class': 'logging.StreamHandler', 'formatter': 'color', 'filters': []},
        'color-verbose': {
            'class': 'logging.StreamHandler',
            'formatter': 'color-verbose',
            'filters': [],
        },
        'sqlhandler': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'sqlformatter',
        },
    },
    # will be expanded, for the moment, I don't care about most outside the project
    'loggers': {
        'django.db.backends': {'handlers': ['sqlhandler'], 'level': LOG_LEVEL,},
        'ff': {'handlers': ['color-verbose'], 'level': LOG_LEVEL, 'propagate': False},
    },
}
if os.getenv('DJANGO_LOG_SQL', False):
    LOGGING['loggers']['django.db.backends']['level'] = logging.DEBUG
else:
    LOGGING['loggers']['django.db.backends']['level'] = logging.INFO

if os.getenv('DJANGO_LOGGING_TREE', None):
    # print tree of configure loggers, understand and debug
    from logging_tree.format import build_description
    logging.config.dictConfig(LOGGING)
    print('logger tree:\n%s', build_description()[:-1])

if os.getenv('FF_LOG_TO_ELASTIC', None):
    from cmreslogging.handlers import CMRESHandler

    LOGGING['loggers']['ff'] = {
        'handlers': ['color-verbose',],
        'level': LOG_LEVEL,
        'propagate': False,
    }
