"""
Django settings for src project.

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

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

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

Developer: Alfred Ntiamoah (Natlink Inc.)
This code is solely for the Digisaver company, Nigeria and can not be 
replicated or reproduce. 
"""

import os
import datetime

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


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'p!f@14li#pvzyf0p0fo9w29h3!0ka#$llak#ftj+f@##$$###@DDFCCCCDEEFFFsdgfsdg5465546gjh^j!-m(4oo@'

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

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'django.contrib.sites',
    'django_filters',
    'allauth',
    'allauth.account',
    'rest_auth.registration',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',
    # 'allauth.socialaccount.providers.google',
    'core',
    'users',
    'files',
    'api.apps.ApiConfig',
    'oauth2_provider',
    'corsheaders',
    'django_db_logger',
    'simple_history',
    
]

SITE_ID = 1 # Reference to you application for site authentication
REST_USE_JWT = True # Enable Json Web Token within  rest-auth, dependent on rest-framework-jwt

# JWT configuration  object. 
# visit  http://getblimp.github.io/django-rest-framework-jwt/#additional-settings for docs 
JWT_AUTH = {
    'JWT_ENCODE_HANDLER':
    'rest_framework_jwt.utils.jwt_encode_handler',

    'JWT_DECODE_HANDLER':
    'rest_framework_jwt.utils.jwt_decode_handler',

    'JWT_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_payload_handler',

    'JWT_PAYLOAD_GET_USER_ID_HANDLER':
    'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    'JWT_RESPONSE_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_response_payload_handler',

    'JWT_SECRET_KEY': SECRET_KEY,
    'JWT_GET_USER_SECRET_KEY': None,
    'JWT_PUBLIC_KEY': None,
    'JWT_PRIVATE_KEY': None,
    'JWT_ALGORITHM': 'HS256',
    'JWT_VERIFY': True,
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3000000000),
    'JWT_AUDIENCE': None,
    'JWT_ISSUER': None,

    'JWT_ALLOW_REFRESH': True,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),

    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_AUTH_COOKIE': None,
}

REST_AUTH_SERIALIZERS = {
    'USER_DETAILS_SERIALIZER ': 'users.serializers.UserSerializer',
}


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django_currentuser.middleware.ThreadLocalUserMiddleware',
    'simple_history.middleware.HistoryRequestMiddleware',
]

ROOT_URLCONF = 'src.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 = 'src.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


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

# Custom user settings
AUTH_USER_MODEL = 'users.UserModel'

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

STATIC_URL = '/static/'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")


# -- Set up DRF to use OAuth2

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        'rest_framework.authentication.SessionAuthentication', # To keep the Browsable API
        # 'rest_framework.authentication.BasicAuthentication', # don't enable, not very secured
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated', # every action should pass authentication unless its set explicitly
    ),
    # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_PAGINATION_CLASS' : 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 100
}

# --- Specify the authentication backends
# emaillogin_project/settings.py
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

AUTHENTICATION_BACKENDS = (
    'users.backends.MyAuthBackend',
    'django.contrib.auth.backends.ModelBackend', # To keep the Browsable API
    'oauth2_provider.backends.OAuth2Backend',
    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)

# ---- AllAuth Authentication configurations
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True

# emaillogin_project/settings.py
# LOGIN_REDIRECT_URL = '/'
# ACCOUNT_LOGOUT_REDIRECT_URL = '/'

# ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL (=settings.LOGIN_URL) #RL to redirect to after a successful e-mail confirmation
# ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL= None
# ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION (=False)


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

# ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1#days
# ACCOUNT_EMAIL_CONFIRMATION_HMAC  = True
# ACCOUNT_EMAIL_VERIFICATION = "mandatory" #user blocks until email is confirmed
# ACCOUNT_EMAIL_SUBJECT_PREFIX = "DigiSaver Email Verification" #Subject-line prefix to use for email messages sent
# ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN =180 #The cooldown period (in seconds) after a confirmation email is sent, during which further emails are not sent
# ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 
# ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT =300 #Time period, in seconds, from last unsuccessful login attempt, during which the user is prohibited from trying to log in




# ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = False
# ACCOUNT_LOGIN_ON_PASSWORD_RESET = False
# ACCOUNT_LOGOUT_REDIRECT_URL = "/"
# ACCOUNT_SESSION_REMEMBER =None
# ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True
# ACCOUNT_USERNAME_BLACKLIST =[]
# ACCOUNT_UNIQUE_EMAIL = True
# ACCOUNT_USERNAME_MIN_LENGTH = 2
# ACCOUNT_USERNAME_REQUIRED = True

# SOCIALACCOUNT_AUTO_SIGNUP =True
# SOCIALACCOUNT_QUERY_EMAIL=ACCOUNT_EMAIL_REQUIRED
# SOCIALACCOUNT_EMAIL_REQUIRED=ACCOUNT_EMAIL_REQUIRED
# SOCIALACCOUNT_STORE_TOKENS=False


#-----  AllAuth Facebook social provider authentication
SOCIALACCOUNT_PROVIDERS = {
    'facebook': {
        'METHOD': 'oauth2',
        'SCOPE': ['email', 'public_profile', 'user_friends'],
        'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
        'INIT_PARAMS': {'cookie': True},
        'FIELDS': [
            'id',
            'email',
            'name',
            'first_name',
            'last_name',
            'verified',
            'locale',
            'timezone',
            'link',
            'gender',
            'updated_time',
            'friends'
        ],
        'EXCHANGE_TOKEN': True,
        # 'LOCALE_FUNC': 'path.to.callable',
        'VERIFIED_EMAIL': False,
        'VERSION': 'v2.12',
    },
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        }
    }
}

# --- You should not have to do this, but I had some problems without it. Probably
# --- just add it you get an error with the ALLOWED_HOSTS.

ALLOWED_HOSTS = ['localhost','127.0.0.1']
CORS_ORIGIN_ALLOW_ALL = True # change for final  deployment 

# Logging configuration 
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(asctime)s %(message)s'
        },
    },
    'handlers': {
        'db_log': {
            'level': 'DEBUG',
            'class': 'django_db_logger.db_log_handler.DatabaseLogHandler'
        },
    },
    'loggers': {
        'db': {
            'handlers': ['db_log'],
            'level': 'DEBUG'
        }
    }
}


# ****************************************************************************************************************
# *
# *
# *
# *
# *
# *
# ****************************************************************************************************************

# General Digisaver Customization variables
CURRENCIES = (("DOLAR", "DO"), ("NAIRA", "NA")) # This is the allowed currencies that operate in the system


# DAccount Customizaton variables 
# ***********************************************************************
REWARD_TYPE = (("REFERRALS", "REF"), ("BONUS", "BON")) 
CALCULATION_METHOD = (("NOTAPPLY", "NO"), ("ASSIGN", "AS"), ("REFERAL", "RE"))
DACCOUNT_STATUS = (("LOCKED", 'LCK'), ("INACTIVE", 'INA'), ("ACTIVE", 'ACT'))
DACCOUNT_TYPE = (("CORE_ACCOUNT", 'CORE'), ("SAVINGS_PLAN", 'SAVINGS'))
WITHDRAWAL_INTERVAL_UNIT = (("MONTHS", 'M'), ("WEEKS", 'W'), ("DAYS", 'D')) # MAX CHAR LENGTH < 10

DACCOUNT_CONFIG = {
    "LOCK_INIT_ACCOUNT":True, # Locking initial account after creation, can only be onlocked by staff a account in manager group
    "LOCK_OUT_PERIOD": 3650000, # Initial account lock period, default 100yrs
    "DEFAULT_WITHDRAWAL_INTERVAL_UNIT": "MONTHS",
    "DEFAULT_WITHDRAWAL_INTERVAL": 1, # Reflects default default withdrawal interval
}

# UAccount Customization settings 
GENDER = (("MALE", "M"), ("FEMALE", "F"), ( "OTHER","O"))
UACCOUNTTYPE = (( "EMPLOYEE", "EM"), ("CUSTOMER", "CU"), ( "REGULAR","RE"))
UACCOUNT_CONFIG = {
    "UACCOUNTTYPE_DEFAULT": "REGULAR",
    "USERNAME_FIELD": "email", # Email is used for authentication
}

# Saving Plan Customization settings
SAVINGS_TYPE = (("SMART_SAVE", "SMART"), ("SELECT_SAVE", "SELECT"),
                    ("SECURE_SAVE", "SECURE"), ("KID_SAVE", "KID"))
SAVINGS_FREQUENCY = (("DAILY", "D"), ("WEEKLY", "W"), ("MONTHLY", "M"))
MINIMUM_INVEST_PERIOD_UNIT = (("YEARS", 'Y'),("MONTHS", 'M'), ("WEEKS", 'W'))
FUND_SOURCE = (("EXTERNAL_BANK", 'EB'), ("CARD_TRANSFER", 'CT'),("PERSONAL_DEPOSIT", 'PD'))
INTEREST_FREQ = (("DAILY", "DA"), ("WEEKLY", "WE"), ("MONTHLY", "MON"), ("YEARLY", "YE"))
INTEREST_CALC_TYPE = (("SIMPLE_INTEREST", "SI"), ("COMPOUND_INTEREST", "CI"))
REPORT_GENERATION_FREQUENCY = (("DAILY", "DA"),("WEEKLY", "WE"), ("MONTHLY", "MON"),
                     ("QUATERLY", "QUA"), ("SEMIANUM", "SEM"), ("YEARLY", "YEA"))
SAVINGSPLAN_CONFIG = {
    "MINIMUM_PRINCIPAL_DEFAULT": 1000.0, # In specified account currency
    "MINIMUM_LUMPSUM": 1000.0, # In specified account currency
    "DEFAULT_CURRENCY": "NAIRA",
    "SAVINGS_TYPE_DEFAULT":"SMART_SAVE", 
    "SAVINGS_FREQUENCY_DEFAULT":"DAILY", 
    "ALLOW_SWIFT_SAVE_DEFAULT": False,
    "ALLOW_ESAVE_DEFAULT": False,
    "ALLOW_MULTIPLE_DEFAULT": False,
    "ALLOW_INTEREST_DEFAULT": False,
    "MINIMUM_INVEST_PERIOD_DEFAULT": 6, # Reflects the units below
    "MINIMUM_INVEST_PERIOD_UNIT_DEFAULT":"MONTHS",
    "FUND_SORUCE_DEFAULT": "PERSONAL_DEPOSIT",
    "REPORT_GEN_SHOW_ACCOUNT_ID": False,
    "REPORT_GEN_SHOW_ACCOUNT_TYPE": False,
    "REPORT_GEN_SHOW_PLAN_TYPE": False,
    "REPORT_GEN_SHOW_ACCOUNT_HOLDER": False,
    "REPORT_GEN_SHOW_TRANSACTIONS": False,
    "REPORT_GEN_SHOW_BALANCE": False,
    "REPORT_GEN_SHOW_INTEREST_SCHEME": False,
    "REPORT_GEN_SHOW_AIM": False,
    "REPORT_GEN_FREQ_DEFAULT": "MONTHLY"
}

EMPLOYEE_TYPES = (('MANAGER','MA'), ('ACCOUNTANT', 'AC'), ('SALES_PERSON', 'SP'), ('OTHER', 'OR'))

DIGISAVER_SYSTEM_CONFIG =   {
    'EMPLOYEE_TYPE_DEFAULT': "OTHER"
}



# hello12345678
# ntiamoah376@yahoo.com
# +233546765

# admin@me.com
# compile111