"""
    Django settings for core project.

    Generated by 'django-admin startproject' using Django 4.1.3.

    For more information on this file, see
    https://docs.djangoproject.com/en/4.1/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/4.1/ref/settings/
"""


from kombu import Queue, Exchange
from pathlib import Path
from decouple import Csv,Config, RepositoryEnv # , config
from django.utils.translation import gettext_lazy as _
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.

BASE_DIR = Path(__file__).resolve().parent.parent
ENV_DIR = Path(__file__).resolve().parent.parent.parent

config = Config(RepositoryEnv(f"{ENV_DIR}/.env"))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY', default="for test", cast=str)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=False, cast=bool)

CSRF_TRUSTED_ORIGINS = config('CSRF_TRUSTED_ORIGINS', default='*' , cast=Csv())
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='' , cast=Csv())


SITE_ID = config('SITE_ID', default=1, cast=int)

# if DEBUG == False:
# SECURE_SSL_REDIRECT = True
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# SECURE_HSTS_SECONDS  = 31536000
# SESSION_COOKIE_SECURE = True
# SESSION_EXPIRE_AT_BROWSER_CLOSE = True

# PAYPAL CONFIGURATION
PAYPAL_CLIENTID = config("PAYPAL_CLIENTID",default='', cast=str)
PAYPAL_SECRETID = config("PAYPAL_SECRETID",default='', cast=str)


# Application definition
INSTALLED_APPS = [
    # Django Apps
    'django.contrib.admin',
    'django.contrib.auth',            # Core authentication framework and its default models.
    'django.contrib.contenttypes',    # Django content type system (allows permissions to be associated with models).
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    # Installed Apps
    'django_extensions',
    'rest_framework',
    'import_export',
    'ckeditor',
    "django_countries",
    "sslserver",
    "mathfilters",
    # 'django_celery_results',
    # "social_django",
    # Our Apps
    "apps.root",
    "apps.accounts",
    "apps.profiles",
    "apps.subscriptions",
    "apps.process",
    "apps.uploads",
    # "apps.shorter",
    "apps.newsletter",
    "apps.userActivities",
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',     # Manages sessions across requests
    '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.clickjacking.XFrameOptionsMiddleware',

    'django.middleware.locale.LocaleMiddleware',
    'apps.accounts.middleware.OneSessionPerUserMiddleware',

    'apps.userActivities.middleware.UserActivityMiddleware'
    # 'social_django.middleware.SocialAuthExceptionMiddleware',   # Manages social_django
]


ROOT_URLCONF = "core.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",
                "apps.subscriptions.context.plans_context.get_plans",
                "apps.subscriptions.context.plans_context.monthly_plans",
                "apps.subscriptions.context.plans_context.paypal_info"

                # "social_django.context_processors.backends",
            ],
            'builtins': [
                # 'dashboard.templatetags.jsonify',
                # 'dashboard.templatetags.colorefy',
                'apps.process.templatetags.has_youtube',
                'apps.process.templatetags.has_youtube_upload',
                'apps.subscriptions.templatetags.valid_extension',
                'apps.subscriptions.templatetags.reached_upload_limit',
                'apps.subscriptions.templatetags.total_videos',
                'apps.subscriptions.templatetags.videos_per_day',
                'apps.subscriptions.templatetags.rest_videos',
            ]
        },
    },
]

WSGI_APPLICATION = "core.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

if DEBUG :
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
else:
    DATABASES = {
        'default': {
            "ENGINE"   : config("SQL_ENGINE", default='django.db.backends.sqlite3', cast=str),
            "NAME"     : config("SQL_DATABASE", default=(BASE_DIR/'db.sqlite3'), cast=str),
            "USER"     : config("SQL_USER", default='user', cast=str),
            "PASSWORD" : config("SQL_PASSWORD", default='password', cast=str),
            "HOST"     : config("SQL_HOST", default='localhost', cast=str),
            "PORT"     : config("SQL_PORT", default='5432', cast=int),
        },
    }


# 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/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'

USE_I18N = True
USE_L10N = True
USE_TZ = True

LANGUAGE_CODE = 'en'
LANGUAGES = [
    ('ar', _('Arabic')),
    ('en', _('English')),
    ('fr', _('French')),
]

LOCALE_PATHS = (
    (BASE_DIR/'locale'),
)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL       = '/static/'
STATIC_ROOT      = (BASE_DIR/'staticfiles')
STATICFILES_DIRS = [(BASE_DIR/'static'),]

MEDIA_URL        = '/media/'
MEDIA_ROOT       = (BASE_DIR/'media')

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Custom Account (User)
AUTH_USER_MODEL = 'accounts.User'

# Email SETTING
EMAIL_BACKEND       = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST          = config("EMAIL_HOST", default='smtp.gmail.com', cast=str)
EMAIL_PORT          = config("EMAIL_PORT", default=587, cast=int)
EMAIL_USE_TLS       = config("EMAIL_USE_TLS", default=True, cast=bool)
EMAIL_HOST_USER     = config("EMAIL_HOST_USER", default='', cast=str)
EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD", default='', cast=str)
DEFAULT_FROM_EMAIL  = EMAIL_HOST_USER


SESSION_COOKIE_AGE = 60 * 60 * 24 * 2
TOKEN_EXPIRY_SECONDS = 60 * 60


CELERY_BROKER_URL        = config("CELERY_BROKER", default="redis://127.0.0.1:6379/0", cast=str)
CELERY_RESULT_BACKEND    = config("CELERY_BACKEND", default="redis://127.0.0.1:6379/0", cast=str)

CELERY_ACCEPT_CONTENT    = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER   = 'json'

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [(config("CHANNELS_REDIS", default="redis://127.0.0.1:6379/0", cast=str))],
        },
    },
}


CELERY_BEAT_SCHEDULE = {
    # 'task-clear-session': {
    #     'task': 'task_clear_session',
    #     "schedule": 5.0,  # five seconds
    # },
}


CELERY_TASK_DEFAULT_QUEUE = 'default'

# Force all queues to be explicitly listed in `CELERY_TASK_QUEUES` to help prevent typos
CELERY_TASK_CREATE_MISSING_QUEUES = False

CELERY_TASK_QUEUES = [
    # need to define default queue here or exception would be raised
    Queue('default',Exchange('tasks'), routing_key='tasks',
          queue_arguments={'x-max-priority': 10}),
]
PRIORITY_STACK = {
    "Basic": 0,
    "Normal": 5,
    "Pro": 9 
}

# CELERY_TASK_ROUTES = {
#     'core.celery.*': {
#         'queue': 'high_priority',
#     },
# }

# dynamic task routing

def route_task(name, args, kwargs, options, task=None, **kw):
    if ':' in name:
        queue, _ = name.split(':')
        return {'queue': queue}
    return {'queue': 'default'}


CELERY_TASK_ROUTES = (route_task,)


# GOOGLE CONF

CLIENT_ID = config('CLIENT_ID',cast=str)
CLIENT_SECRET = config('CLIENT_SECRET',cast=str)

REDIRECT_URI = config('REDIRECT_URI', cast=str)

os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'


CLIENT_SECRETS_FILE ="json_credentials.json"
JSON_PATH = os.path.join(os.getcwd(),"apps/uploads",CLIENT_SECRETS_FILE)
SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

# # Social Auth
# SOCIAL_AUTH_JSONFIELD_ENABLED = True
#
# # Authentification Backends Config
# AUTHENTICATION_BACKENDS = (
#     'qsocial_core.backends.apple.AppleIdAuth',
#     'social_core.backends.google.GoogleOAuth2',

#     'django.contrib.auth.backends.ModelBackend',
# )

# # LOGIN_URL = 'account:signin'
# # LOGIN_REDIRECT_URL = 'landing:index'
# # LOGOUT_URL = 'account:signout'
# # LOGOUT_REDIRECT_URL = 'account:signin'

# # Google Oauth 2
# SOCIAL_AUTH_URL_NAMESPACE = 'social'

# SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY', cast=str, default="" )
# SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET', cast=str, default="")

# local logs
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "root": {"level": "INFO", "handlers": ["file"]},
    "handlers": {
        "file": {
            "level": "INFO",
            "class": "logging.FileHandler",
            "filename": "logs/django.log",
            "formatter": "app",
        },
    },
    "loggers": {
        "django": {
            "handlers": ["file"],
            "level": "INFO",
            "propagate": True
        },
    },
    "formatters": {
        "app": {
            "format": (
                u"%(asctime)s [%(levelname)-8s] "
                "(%(module)s.%(funcName)s) %(message)s"
            ),
            "datefmt": "%Y-%m-%d %H:%M:%S",
        },
    },
}