"""
Django settings for boltstream project.

Generated by "django-admin startproject" using Django 2.0.3.

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

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

import os

import sentry_sdk
from django.contrib.messages import constants as message_constants
from environ import Env
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.django import DjangoIntegration

ENV = Env()

# Sentry
sentry_sdk.init(
    dsn=ENV.str("SENTRY_DSN", None),
    environment=ENV.str("SENTRY_ENVIRONMENT", None),
    release=ENV.str("SENTRY_RELEASE", None),
    integrations=[CeleryIntegration(), DjangoIntegration()],
)


# 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.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ENV.str("SECRET_KEY", "debug-secret")

# SECURITY WARNING: don"t run with debug turned on in production!
DEBUG = ENV.bool("DEBUG", True)

ALLOWED_HOSTS = ["*"]
APP_HOST = ENV.str("APP_HOST", "localhost")


# Application definition

INSTALLED_APPS = [
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.humanize",
    "rest_framework",
    "rest_framework.authtoken",
    "bootstrap4",
    "corsheaders",
    "boltstream",
    "django.contrib.admin",
]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    "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",
]

ROOT_URLCONF = "boltstream.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 = "boltstream.wsgi.application"

# Logging
LOG_LEVEL = ENV.str("DJANGO_LOG_LEVEL", "INFO").upper()
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"console": {"level": LOG_LEVEL, "class": "logging.StreamHandler"}},
    "loggers": {"boltstream": {"handlers": ["console"], "level": LOG_LEVEL}},
}

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

DATABASES = {
    "default": ENV.db_url(
        default="sqlite:///{}".format(os.path.join(BASE_DIR, "db.sqlite3"))
    )
}

CACHES = {"default": ENV.cache_url(default="dummycache://")}

AUTHENTICATION_BACKENDS = ("boltstream.auth.UsernameOrEmailModelBackend",)

AUTH_USER_MODEL = "boltstream.User"
AUTH_PROFILE_MODEL = "boltstream.Profile"
SESSION_ENGINE = ENV.str(
    "SESSION_ENGINE", "django.contrib.sessions.backends.signed_cookies"
)
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_NAME = ENV.str("SESSION_COOKIE_NAME", "sessionid")
SESSION_COOKIE_DOMAIN = ENV.str("SESSION_COOKIE_DOMAIN", None)
SESSION_COOKIE_SECURE = ENV.bool("REQUIRE_HTTPS", not DEBUG)

CSRF_USE_SESSIONS = True
CSRF_TRUSTED_ORIGINS = ENV.list("CSRF_TRUSTED_ORIGINS", default=[])
if SESSION_COOKIE_DOMAIN:
    CSRF_TRUSTED_ORIGINS.append(SESSION_COOKIE_DOMAIN)

LOGIN_URL = "/sign-in"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/sign-in"
# SECURE_SSL_REDIRECT = ENV.bool("REQUIRE_HTTPS", not DEBUG)

MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
MESSAGE_TAGS = {message_constants.ERROR: "danger"}

# CORS
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = False

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

# Celery
BROKER_URL = ENV.str("BROKER_URL", None)


# Internationalization
# https://docs.djangoproject.com/en/2.0/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.0/howto/static-files/
STATICFILES_STORAGE = ENV.str(
    "STATICFILES_STORAGE", "django.contrib.staticfiles.storage.StaticFilesStorage"
)
STATIC_URL = ENV.str("STATIC_URL", "/static/")
STATIC_ROOT = ENV.str("STATIC_ROOT", os.path.join(BASE_DIR, "static"))
AWS_STORAGE_BUCKET_NAME = ENV.str("AWS_STORAGE_BUCKET_NAME", None)
AWS_S3_CUSTOM_DOMAIN = ENV.str("AWS_S3_CUSTOM_DOMAIN", None)
AWS_S3_REGION_NAME = ENV.str("AWS_S3_REGION_NAME", None)
AWS_S3_ENDPOINT_URL = ENV.str("AWS_S3_ENDPOINT_URL", None)
AWS_DEFAULT_ACL = "public-read"

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

RTMP_SECRET = ENV.str("RTMP_SECRET", None)
EXPIRE_VIEWER_SECONDS = ENV.int("EXPIRE_VIEWER_SECONDS", 60)
RTMP_ENDPOINT = ENV.str("RTMP_ENDPOINT", None)

FFMPEG_PATH = ENV.str("FFMPEG_PATH", "ffmpeg")
FFPROBE_PATH = ENV.str("FFPROBE_PATH", "ffprobe")

# API
# http://www.django-rest-framework.org/
# https://django-oauth-toolkit.readthedocs.io/en/latest/index.html
REST_FRAMEWORK = {
    "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning",
    "DEFAULT_VERSION": ENV.str("DEFAULT_API_VERSION", "v1"),
    "ALLOWED_VERSIONS": ENV.list("ALLOWED_API_VERSIONS", default=["v1"]),
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
    ),
    "DEFAULT_FILTER_BACKENDS": (
        "django_filters.rest_framework.DjangoFilterBackend",
        "rest_framework.filters.OrderingFilter",
    ),
    "DEFAULT_RENDERER_CLASSES": (
        "rest_framework.renderers.JSONRenderer",
        "rest_framework.renderers.BrowsableAPIRenderer",
    ),
    "DEFAULT_PARSER_CLASSES": (
        "rest_framework.parsers.FormParser",
        "rest_framework.parsers.MultiPartParser",
        "rest_framework.parsers.JSONParser",
        "rest_framework.parsers.FileUploadParser",
    ),
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 20,
}

# ACRCloud
ACRCLOUD_API_ENDPOINT = ENV.str("ACRCLOUD_API_ENDPOINT", "https://api.acrcloud.com/")
ACRCLOUD_API_SIGNATURE_VERSION = ENV.str("ACRCLOUD_API_SIGNATURE_VERSION", "1")
ACRCLOUD_CONSOLE_ACCESS_KEY = ENV.str("ACRCLOUD_CONSOLE_ACCESS_KEY", None)
ACRCLOUD_CONSOLE_ACCESS_SECRET = ENV.str("ACRCLOUD_CONSOLE_ACCESS_SECRET", None)
ACRCLOUD_BUCKET_NAME = ENV.str("ACRCLOUD_BUCKET_NAME", None)

# SportRadar
SPORTRADAR_API_ENDPOINT = ENV.str(
    "SPORTRADAR_API_ENDPOINT", "https://api.sportradar.us/"
)
SPORTRADAR_API_KEY = ENV.str("SPORTRADAR_API_KEY", None)
