import os

from pathlib import Path
from datetime import timedelta
from celery.schedules import crontab

from django.utils.translation import gettext_lazy as _


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


SECRET_KEY = os.environ.get(
    'SECRET_KEY',
    default='m8/o)3$n^03w)mxgvnrxb46__@6qnte9l0dkb7$6%lpbcox+v!'
)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = int(os.environ.get('DEBUG', default=1))

# 'DJANGO_ALLOWED_HOSTS' should be a single string of hosts with a space between each.
# For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]'
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", default='*').split(" ")


# Application definition

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

    'rest_framework',
    'django_filters',
    'rosetta',
    'djoser',
    'djmoney',
    'djmoney.contrib.exchange',
    'corsheaders',

    'apps.account.apps.AccountConfig',
    'apps.transaction.apps.TransactionConfig',
    'apps.common.apps.CommonConfig',
    'apps.authentication.apps.AuthenticationConfig'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware'
]

ROOT_URLCONF = 'project.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'
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'),
        'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')),
        'USER': os.environ.get('SQL_USER'),
        'PASSWORD': os.environ.get('SQL_PASSWORD'),
        'HOST': os.environ.get('SQL_HOST'),
        'PORT': os.environ.get('SQL_PORT'),
    }
}

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

AUTH_USER_MODEL = 'authentication.User'

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

LANGUAGE_CODE = 'uk'
LANGUAGES = [
    ('en', _('English')),
    ('uk', _('Ukrainian'))
]

LOCALE_PATHS = (
    BASE_DIR / 'locale',
)

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

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

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# ------------------------------------------ #
#                django-money                #
# ------------------------------------------ #
DEFAULT_CURRENCY = 'EUR'

EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend'
FIXER_ACCESS_KEY = 'f5a898dbf45d15d8aa6eca7af3f372e1'

# ------------------------------------------ #
#                  Celery                    #
# ------------------------------------------ #
CELERY_BROKER_URL = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379')
CELERY_RESULT_BACKEND = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379')
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'


CELERY_BEAT_SCHEDULE = {
    'update_rates': {
        'task': 'apps.user.tasks.update_rates',
        'schedule': crontab(hour="*/1"),
    }
}

# ------------------------------------------ #
#           Django REST Framework            #
# ------------------------------------------ #
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler',
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}

# ------------------------------------------ #
#                   djoser                   #
# ------------------------------------------ #
DJOSER = {
    # Name of a field in User model to be used as login field
    'LOGIN_FIELD': 'email',
    # If True user will be required to click activation
    # link sent in email after:
    # * creating an account
    # * updating their email
    'SEND_ACTIVATION_EMAIL': True,
    'ACTIVATION_URL': '/activate/{uid}/{token}',
    'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}',
    'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}',
    # If True, you need to pass re_password to /users/
    # endpoint, to validate password equality.
    'USER_CREATE_PASSWORD_RETYPE': True,
    'PASSWORD_RESET_CONFIRM_RETYPE': True,
    # If True, register or activation endpoint
    # will send confirmation email to user.
    'SEND_CONFIRMATION_EMAIL': True,
    'SERIALIZERS': {
        'user_create': 'apps.user.serializers.UserCreateSerializer'
    }
}

# ------------------------------------------ #
#               Simple JWT                   #
# ------------------------------------------ #
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': True,
    'AUTH_HEADER_TYPES': ('JWT',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'id',
}

CORS_ALLOW_ALL_ORIGINS = True

[((14, 13, 17, 1), 'os.environ.get', 'os.environ.get', (), '', False, 'import os\n'), ((142, 14, 142, 46), 'os.path.join', 'os.path.join', ({(142, 27, 142, 35): 'BASE_DIR', (142, 37, 142, 45): '"""static"""'}, {}), "(BASE_DIR, 'static')", False, 'import os\n'), ((157, 20, 157, 78), 'os.environ.get', 'os.environ.get', ({(157, 35, 157, 51): '"""REDIS_LOCATION"""', (157, 53, 157, 77): '"""redis://127.0.0.1:6379"""'}, {}), "('REDIS_LOCATION', 'redis://127.0.0.1:6379')", False, 'import os\n'), ((158, 24, 158, 82), 'os.environ.get', 'os.environ.get', ({(158, 39, 158, 55): '"""REDIS_LOCATION"""', (158, 57, 158, 81): '"""redis://127.0.0.1:6379"""'}, {}), "('REDIS_LOCATION', 'redis://127.0.0.1:6379')", False, 'import os\n'), ((20, 12, 20, 46), 'os.environ.get', 'os.environ.get', (), '', False, 'import os\n'), ((216, 29, 216, 49), 'datetime.timedelta', 'timedelta', (), '', False, 'from datetime import timedelta\n'), ((217, 30, 217, 47), 'datetime.timedelta', 'timedelta', (), '', False, 'from datetime import timedelta\n'), ((24, 16, 24, 67), 'os.environ.get', 'os.environ.get', (), '', False, 'import os\n'), ((87, 18, 87, 76), 'os.environ.get', 'os.environ.get', ({(87, 33, 87, 45): '"""SQL_ENGINE"""', (87, 47, 87, 75): '"""django.db.backends.sqlite3"""'}, {}), "('SQL_ENGINE', 'django.db.backends.sqlite3')", False, 'import os\n'), ((89, 16, 89, 42), 'os.environ.get', 'os.environ.get', ({(89, 31, 89, 41): '"""SQL_USER"""'}, {}), "('SQL_USER')", False, 'import os\n'), ((90, 20, 90, 50), 'os.environ.get', 'os.environ.get', ({(90, 35, 90, 49): '"""SQL_PASSWORD"""'}, {}), "('SQL_PASSWORD')", False, 'import os\n'), ((91, 16, 91, 42), 'os.environ.get', 'os.environ.get', ({(91, 31, 91, 41): '"""SQL_HOST"""'}, {}), "('SQL_HOST')", False, 'import os\n'), ((92, 16, 92, 42), 'os.environ.get', 'os.environ.get', ({(92, 31, 92, 41): '"""SQL_PORT"""'}, {}), "('SQL_PORT')", False, 'import os\n'), ((121, 11, 121, 23), 'django.utils.translation.gettext_lazy', '_', ({(121, 13, 121, 22): '"""English"""'}, {}), "('English')", True, 'from django.utils.translation import gettext_lazy as _\n'), ((122, 11, 122, 25), 'django.utils.translation.gettext_lazy', '_', ({(122, 13, 122, 24): '"""Ukrainian"""'}, {}), "('Ukrainian')", True, 'from django.utils.translation import gettext_lazy as _\n'), ((167, 20, 167, 39), 'celery.schedules.crontab', 'crontab', (), '', False, 'from celery.schedules import crontab\n'), ((88, 47, 88, 83), 'os.path.join', 'os.path.join', ({(88, 60, 88, 68): 'BASE_DIR', (88, 70, 88, 82): '"""db.sqlite3"""'}, {}), "(BASE_DIR, 'db.sqlite3')", False, 'import os\n'), ((11, 11, 11, 25), 'pathlib.Path', 'Path', ({(11, 16, 11, 24): '__file__'}, {}), '(__file__)', False, 'from pathlib import Path\n')]