"""
Django settings for futplus project.

Generated by 'django-admin startproject' using Django 3.2.12.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import copy
import os
import sys
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
import sentry_sdk
from decouple import config
from django.contrib import messages
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.redis import RedisIntegration
from sentry_sdk.integrations.tornado import TornadoIntegration

# todo : in new development
# if getattr(sys, 'frozen', False):
#     BASE_DIR = os.path.dirname(sys.executable)
# else:
#     BASE_DIR = Path(__file__).resolve().parent.parent

BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = 'django-insecure-g98^8#c471ttj2n2lj)6z#axow5_^wfvqiy*8m&k=1lmhhgk#('
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = True
DEBUG = config('DEBUG', default=False, cast=bool)

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.postgres',
    'futplus',
    'accounts',
    'sbc',
    'sniper',
    'trade',
    'squad_battle',
    'financial',
    # 'gamepad',
    'utils',
    'django_tables2',
    'crispy_forms',
    'customrolepermissions',
    'rolepermissions',
    'django_select2',
    'django_filters',
    'extra_views',
    'compressor',
]

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',
]

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # other finders..
    'compressor.finders.CompressorFinder',
)

ROOT_URLCONF = 'futplus.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        },
    },
]

WSGI_APPLICATION = 'futplus.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': BASE_DIR / 'db.sqlite3',
    # }
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': 'navac#CFG',
        # 'PASSWORD': config('DB_PASSWORD', default=''),
        'HOST': config('DB_HOST'),
        'PORT': config('DB_PORT'),
        # 'PORT': '5432' # database port,
        # 'PORT': '6434',  # pgbouncer port
    },
    'logs': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'futpluslog',
        'USER': 'futplus',
        'PASSWORD': '123ymgMM3211',
        'HOST': '23.88.115.241',
        'PORT': '5434', # database port
        # 'PORT': '6434', # pgbouncer port
    },
}
DATABASES['default_pgbouncer'] = copy.deepcopy(DATABASES.get('default'))
DATABASES['default_pgbouncer']['PORT'] = '6434'
DATABASES['logs_pgbouncer'] = copy.deepcopy(DATABASES.get('logs'))
DATABASES['logs_pgbouncer']['PORT'] = '6434'

# 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',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Tehran'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

DATA_DIR = os.path.join(BASE_DIR, '.data')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(DATA_DIR, 'static')
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

if DEBUG is False and False:
    SENTRY_DSN = config('SENTRY_DSN')
    sentry_sdk.init(
        dsn=SENTRY_DSN,
        integrations=[DjangoIntegration(), CeleryIntegration(), RedisIntegration(), TornadoIntegration()],

        # 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
    )

CELERY_BROKER = config('CELERY_BROKER')
CELERY_BACKEND = config('CELERY_BACKEND', default=None)
SERVER_TYPE = config('SERVER_TYPE', default='')
FLOWER_ADDRESS = config('FLOWER_ADDRESS')
try:
    CONSOLE_NAME = config('CONSOLE_NAME')
except:
    CONSOLE_NAME = '************'
CONSOLE_NAME_LIST = config('CONSOLE_NAME_LIST', default='').split(',') if config('CONSOLE_NAME_LIST', default='') else []
if not CONSOLE_NAME_LIST and CONSOLE_NAME != '************':
    CONSOLE_NAME_LIST.append(CONSOLE_NAME)
CELERY_BROKER_CONNECTION_RETRY = True
CELERY_BROKER_CONNECTION_MAX_RETRIES = 400

SITE_ID = 1

LOGIN_REDIRECT_URL = '/'

ROLEPERMISSIONS_MODULE = 'futplus.roles'
ROLEPERMISSIONS_REDIRECT_TO_LOGIN = True
ROLEPERMISSIONS_REGISTER_ADMIN = False

DEFAULT_PORT = config('DEFAULT_PORT', default=None)
SNIPER_SERVER = config('SNIPER_SERVER', default=False, cast=bool)

MESSAGE_TAGS = {
    messages.DEBUG: 'alert-info',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}

COMPRESS_ENABLED = True
COMPRESS_OFFLINE = True
LIBSASS_OUTPUT_STYLE = 'compressed' if COMPRESS_ENABLED else 'expanded'
COMPRESS_PRECOMPILERS = [('text/x-scss', 'django_libsass.SassCompiler'), ]

CACHES = {
    # … default cache config and others
    'default': {
        "BACKEND": "django.core.cache.backends.filebased.FileBasedCache",
        "LOCATION": os.path.join(BASE_DIR, '.data/default_cache/'),
        # 'TIMEOUT': 60 * 60 * 1,  # 5 hours
        'OPTIONS': {
            'MAX_ENTRIES': 10
        }
    },
    "select2": {
        "BACKEND": "django.core.cache.backends.filebased.FileBasedCache",
        "LOCATION": os.path.join(BASE_DIR, '.data/select2_cache/'),
        'TIMEOUT': 60 * 60 * 1,  # 5 hours
        'OPTIONS': {
            'MAX_ENTRIES': 200
        }
    },
    # 'players_log': {
    #     'BACKEND': 'django_redis.cache.RedisCache',
    #     # 'LOCATION': "redis://default:X56fmJ2HhqH2b8ubMQl9UFZmdsr6OyIV@yymtgkcj.lexoyacloud.ir:30005",
    #     'LOCATION': "redis://default:X56fmJ2HhqH2b8ubMQl9UFZmdsr6OyIV@yymtgkcj.lexoyacloud.ir:30005",
    #     'OPTIONS': {
    #         "PASSWORD": 'X56fmJ2HhqH2b8ubMQl9UFZmdsr6OyIV',
    #     },
    # },
    # 'print_log': {
    #     'BACKEND': 'django_redis.cache.RedisCache',
    #     'LOCATION': "redis://:b78yNPYu4T0XwQITG6sMNlJz@sabalan.liara.cloud:32815/0",
    #     # 'LOCATION': "redis://default:sZXEfUcopHaQIPdHBgRNAU2xNLKgE3Ii@amrshojh.lexoyacloud.ir:30009",
    #     # 'OPTIONS': {
    #     #     "PASSWORD": 'sZXEfUcopHaQIPdHBgRNAU2xNLKgE3Ii',
    #     # },
    # },
    'print_log': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': "redis://:abtin@@123@23.88.115.241:7379/0",
    },
    'diskcache_alternative': {
        "BACKEND": "django.core.cache.backends.filebased.FileBasedCache",
        "LOCATION": os.path.join(BASE_DIR, '.data/diskcache_alternative/'),
    }
}

# Tell select2 which cache configuration to use:
SELECT2_CACHE_BACKEND = "select2"