import os
from pathlib import Path
from django.urls import reverse_lazy
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from .config import *

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Add Your Required Allow Host
if not DEBUG:
    ALLOWED_HOSTS = [
        'ptcoffee-dev.windmillapps.org',
        'ptcoffee.com',
        'www.ptcoffee.com',
        'porttownsendcoffee.com',
        'www.porttownsendcoffee.com',
    ]
else:
    ALLOWED_HOSTS = ['192.168.68.106', '127.0.0.1', 'localhost']

INTERNAL_IPS = [
    '127.0.0.1',
    'localhost',
]

# Application definition
INSTALLED_APPS = [
    # Core
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    # 3rd Party
    'django_filters',
    'storages',
    'localflavor',
    'debug_toolbar',
    'django_celery_beat',
    'django_celery_results',
    'anymail',
    'compressor',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'analytical',
    'captcha',

    # Local
    'accounts.apps.AccountsConfig',
    'core.apps.CoreConfig',
    'storefront.apps.StorefrontConfig',
    'dashboard.apps.DashboardConfig',
]

# Middlewares
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',
    'ptcoffee.middleware.TimezoneMiddleware',
    'ptcoffee.middleware.RestrictStaffToAdminMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

ROOT_URLCONF = 'ptcoffee.urls'

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

WSGI_APPLICATION = 'ptcoffee.wsgi.application'


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

DATABASES = {
    'default': DATABASE_CONFIG
}

CACHES = {'default': CACHE_CONFIG}

SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

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

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
)

AUTH_USER_MODEL = 'accounts.User'
ACCOUNT_FORMS = {'signup': 'accounts.forms.UserSignupForm'}
ACCOUNT_ADAPTER = 'accounts.adapter.AccountAdapter'
LOGIN_REDIRECT_URL = reverse_lazy('storefront:product-list')

# ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'

ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_UNIQUE_EMAIL = True


# Internationalization
# https://docs.djangoproject.com/en/3.2/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/3.2/howto/static-files/

STATIC_URL = '/static/'
if DEBUG:
    STATIC_ROOT = BASE_DIR / 'public'
else:
    STATIC_ROOT = STATIC_ROOT_PATH
STATICFILES_DIRS = [BASE_DIR / 'static']
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

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

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


# Email
EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend'

ANYMAIL = ANYMAIL_CONFIG

ADMINS = (
    ('Nathan Chapman', ADMIN_EMAIL),
)

MANAGERS = ADMINS

TEMPLATED_EMAIL_BACKEND = 'templated_email.backends.vanilla_django.TemplateBackend'


# Site ID
SITE_ID = 1

# Logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'formatters': {
        'verbose': {
            'format': '{name} {levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filters': ['require_debug_false'],
            'filename': '/var/log/django-ptcoffee/debug.log',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'django.file': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

CART_SESSION_ID = 'cart'

DEFAULT_COUNTRY = 'US'
DEFAULT_CURRENCY = 'USD'
DEFAULT_DECIMAL_PLACES = 2
DEFAULT_MAX_DIGITS = 12
DEFAULT_CURRENCY_CODE_LENGTH = 3


# Celery - prefix with CELERY_
CELERY_BROKER_URL = CACHE_CONFIG['LOCATION']
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
CELERY_CACHE_BACKEND = CELERY_BROKER_URL
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_TRACK_STARTED = True
CELERY_TIMEZONE = 'US/Mountain'

# Sentry
sentry_sdk.init(
    dsn=SENTRY_DSN,
    environment=SENTRY_ENV,
    integrations=[DjangoIntegration()],

    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for performance monitoring.
    # We recommend adjusting this value in production.
    traces_sample_rate=1.0,

    # If you wish to associate users to errors (assuming you are using
    # django.contrib.auth) you may enable sending PII data.
    send_default_pii=True
)
