"""
Django settings for enterprise_website project.

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

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

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

import os
import json
from custom_tags.management.commands.secret_keys import Command, PLATFORM
from pathlib import Path

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

# read secret keys and sensitive dataSITE_ID
SECRET_FILE = "keys.json"
KEYS = Command().load_keys_file(SECRET_FILE)

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = KEYS.get("SECRET_KEY", "")

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

ALLOWED_HOSTS = [
    '192.168.0.4',
    '127.0.0.1',
]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.sites',
    'django.contrib.contenttypes',  # https://docs.djangoproject.com/en/2.0/ref/contrib/contenttypes/#module-django.contrib.contenttypes
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',  # https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#module-django.contrib.staticfiles
    'rest_framework',  # support for rest apps

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',

    'webprogram.apps.WebprogramConfig',
    'home.apps.HomeConfig',
    'todo.apps.TodoConfig',
    'language_management.apps.LanguageManagementConfig',
    'polls.apps.PollsConfig',
    'custom_tags.apps.CustomTagsConfig',
    'location_management.apps.LocationManagementConfig',
    'user_management.apps.UserManagementConfig',
    'timezone_management.apps.TimezoneManagementConfig',
    'easy_timezones',  # allow timezone per user https://github.com/Miserlou/django-easy-timezones
    'django_countries',  # https://github.com/SmileyChris/django-countries/
    'phonenumber_field',  # https://github.com/stefanfoulis/django-phonenumber-field
    'rosetta',
    'channels',
]

# during the request phase, where middleware is applied first-to-last
# during the response phase, where middleware is run in reverse order last-to-first
# hints about ordering MIDDLEWARE https://docs.djangoproject.com/en/2.0/ref/middleware/#middleware-ordering
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    #'django.middleware.cache.UpdateCacheMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware', #Manages sessions across requests
    'django.middleware.locale.LocaleMiddleware', # https://docs.djangoproject.com/en/2.1/topics/i18n/translation/#how-django-discovers-language-preference
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware', #Associates users with requests using sessions.
    'django.contrib.messages.middleware.MessageMiddleware',
    #'django.middleware.cache.FetchFromCacheMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'easy_timezones.middleware.EasyTimezoneMiddleware',  # https://github.com/Miserlou/django-easy-timezones
    #'django.contrib.redirects.middleware.RedirectFallbackMiddleware',  # https://docs.djangoproject.com/en/2.0/ref/contrib/redirects/
]

ROOT_URLCONF = 'enterprise_website.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            # https://docs.djangoproject.com/en/2.0/ref/templates/api/#using-requestcontext
            '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 = 'enterprise_website.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'productsDB',                      # Or path to database file if using sqlite3.
        'USER': KEYS.get("DB_USER_{}".format(PLATFORM), KEYS.get("DB_USER", "root")),
        'PASSWORD': KEYS.get("DB_PASS_{}".format(PLATFORM), KEYS.get("DB_PASS", "")),
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}

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

# for testing mailing
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

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

LANGUAGE_CODE = 'en-us'  # default language to use in my site
# https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
# it is better to convert time per user timezone. Django converts timezones to UTC when USE_TZ is enabled
# if easy_timezones is enabled be careful as it caches TIME_ZONE in cookies as 'django_timezone'
TIME_ZONE = 'America/Bogota'  # for my site. All are saved to databases as UTC regardless
#TIME_ZONE = 'UTC'  # Default time zone recommended UTC to be international and for arithmetic

USE_I18N = True

USE_L10N = True

# With USE_TZ = True django expects aware datetimes on the database layer.
# Any value you get from a model or form field will be aware.
# If Django encounters a naïve datetime, it interprets it as local time (TIME_ZONE)
# of the current time zone and logs a warning.
USE_TZ = True


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

# All settings common to all environments
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]  # https://docs.djangoproject.com/en/2.0/ref/settings/#prefixes-optional
# FIX SITE_ID = 1 fixes "Site matching query does not exist."
SITE_ID = 1  # https://docs.djangoproject.com/en/2.0/ref/settings/#sites

# easy_timezones
# https://github.com/Miserlou/django-easy-timezones
GEOIP_DATABASE = './GeoLiteCity.dat'
GEOIPV6_DATABASE = './GeoLiteCityv6.dat'

# to give color to messages
from django.contrib.messages import constants as messages
# https://simpleisbetterthancomplex.com/tips/2016/09/06/django-tip-14-messages-framework.html
MESSAGE_TAGS = {
    messages.DEBUG: 'alert-info',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}

# language_management
from django.utils.translation import gettext_noop
# https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
LANGUAGES = (
    ('en', gettext_noop('English')),
    ('es', gettext_noop('Spanish')),
    ('pt', gettext_noop('Portuguese')),
    ('fr', gettext_noop('French')),
    ('it', gettext_noop('Italian')),
    ('ja', gettext_noop('Japanese')),
    )
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

# rosetta
# http://django-rosetta.readthedocs.io/en/latest/settings.html
ROSETTA_REQUIRES_AUTH = True  # restrict users
ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS = True  # suggest translations
YANDEX_TRANSLATE_KEY = KEYS.get("YANDEX_TRANSLATE_KEY", "")
ROSETTA_LANGUAGE_GROUPS = True  # choose groups to translate
ROSETTA_SHOW_AT_ADMIN_PANEL = True  # in admin
ROSETTA_STORAGE_CLASS = 'rosetta.storage.CacheRosettaStorage'  # 'rosetta.storage.SessionRosettaStorage'
ROSETTA_SHOW_OCCURRENCES = True
# ROSETTA_LANGUAGES = ""  # more languages


def ROSETTA_ACCESS_CONTROL_FUNCTION(user):
    # only staff members can use rosetta
    return user.is_staff is True and user.is_active is True


# login
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
LOGIN_URL = '/accounts/login'  # must be absolute path
AUTH_USER_MODEL = 'user_management.SiteUser'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
EMAIL_HOST = 'localhost'
EMAIL_PORT = '1025'

# logging  https://docs.djangoproject.com/en/dev/topics/logging/
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        #'special': {
        #    '()': 'project.logging.SpecialFilter',
        #    'foo': 'bar',
        #},
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
        'console':{
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': [], #['special']
        }
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
    }
}

# django-rest-framework
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ],
    # allows you to control how many objects per page are returned
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

# channels
ASGI_APPLICATION = "enterprise_website.routing.application"
