"""
Django settings for deliverables project.

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

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

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

import os

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("DEPLOYMENT_SECRET",'ouu5awo+ny)_4@x2e2v6cm5aur4rdli(0e#tu0hvekurbbf)*o')

# SECURITY WARNING: don't run with debug turned on in production!
if "UNSAFE_DEBUG" in os.environ:
    DEBUG = True
else:
    DEBUG = False

ALLOWED_HOSTS = ['*']
if "DEPLOYMENT_HOST" in os.environ:
    ALLOWED_HOSTS.append(os.environ["DEPLOYMENT_HOST"])
if "CALLBACK_HOST" in os.environ:
    ALLOWED_HOSTS.append(os.environ["CALLBACK_HOST"])

ALLOWED_CIDR_NETS = []
if "ALLOWED_HOSTS_CIDR" in os.environ:
    ALLOWED_CIDR_NETS = os.environ["ALLOWED_HOSTS_CIDR"].split(",")

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gnm_deliverables',
    'rabbitmq',
    'django_nose',
    'rest_framework'
]

TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
    "--with-coverage",
    "--cover-package=gnm_deliverables,rabbitmq"
]
MIDDLEWARE = [
    'allow_cidr.middleware.AllowCIDRMiddleware',
    '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 = 'gnm_deliverables.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 = 'wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ.get("DB_NAME", "pluto-deliverables"),
        'USER': os.environ.get("DB_USER", "pluto-deliverables"),
        'PASSWORD': os.environ.get("DB_PASSWD", "pluto-deliverables"),
        'HOST': os.environ.get("DB_HOST", 'localhost'),
        'PORT': os.environ.get("DB_PORT", "5432"),
    }
}

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

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

### Vidispine configuration. These should be the locations that the _server portion_ can access VS, not the browser.
VIDISPINE_URL=os.environ.get("VIDISPINE_URL","http://vidispine.local:80")
VIDISPINE_USER=os.environ.get("VIDISPINE_USER","admin")
VIDISPINE_PASSWORD=os.environ.get("VIDISPINE_PASSWORD","admin")
### URI that the browser can use to contact Vidispine
VIDISPINE_CLIENT_URI = os.environ.get("VIDISPINE_CLIENT_URI","https://vidispine.local")

### DEPLOYMENT_ROOT is the place we are deploted, i.e. the full base URL that the client's browser will connect to us at.
DEPLOYMENT_ROOT = os.environ.get("DEPLOYMENT_ROOT", "http://localhost:9000")
### VS_CALLBACK_ROOT is the place that Vidispine should expect to find us for notifications.  In normal deployment, this
#### is _in-cluster_ so should be an http:// link to our k8s Service and NOT the external-facing https:// one.
VS_CALLBACK_ROOT = os.environ.get("CALLBACK_ROOT", "http://localhost:9000")

### Location that the browser can find the media atom tool
MEDIA_ATOM_TOOL_URI = os.environ.get("MEDIA_ATOM_TOOL_URI", "https://media-atom-tool.local")

### Message queue configuration. These should be the locations that the _server portion_ can access Rabbitmq
RABBITMQ_HOST = os.environ.get("RABBITMQ_HOST", "localhost")
RABBITMQ_PORT = int(os.environ.get("RABBITMQ_PORT", "5672"))
RABBITMQ_VHOST = os.environ.get("RABBITMQ_VHOST", "prexit")
RABBITMQ_EXCHANGE = 'pluto-deliverables'
RABBITMQ_USER = os.environ.get("RABBITMQ_USER","pluto-ng")
RABBITMQ_PASSWD = os.environ.get("RABBITMQ_PASSWD","")

### Locations where things live
GNM_DELIVERABLES_SAN_ROOT       = os.environ.get("DELIVERABLES_ROOT_PATH", "/media/shared")
GNM_DELIVERABLES_SAN_ROOT_LOCAL = os.environ.get("DELIVERABLES_CLIENT_PATH", "/Volumes/shared")

### Launch detector integration
LAUNCH_DETECTOR_SHARED_KEY = os.environ.get("LAUNCH_DETECTOR_SHARED_KEY","something_here")
LAUNCH_DETECTOR_URL = os.environ.get("LAUNCH_DETECTOR_URL","launch-detector-not-set")

# Transcode presets to use.  The first value is a regex to match against the MIME type, the second is the name of the VS preset
TRANSCODE_PRESETS = {
    r'^video/': "lowres",
    r'^audio/': "lowaudio",
    r'^image/': "lowimage",
    r'^application/x-mxf': "lowres",
    r'^application/x-material-exchange-format': "lowres"
}

# Map of a valid CDS route name to the (lowercase) platform designation.
# No validation of the route name is made here, if the route does not exist then CDS will throw an error
CDS_ROUTE_MAP = {
    "mainstream": "MainstreamMedia.xml",
    "dailymotion": "DailyMotion.xml"
}

# Content API integration details
CAPI_KEY = os.environ.get("CAPI_KEY")
CAPI_BASE = os.environ.get("CAPI_BASE")
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
}

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

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

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'normal': {
            'format': "{asctime} {name}|{funcName} [{levelname}] {message}",
            'style': "{"
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'normal',
        },
    },
    'loggers': {
        'pika': {
            'level': 'ERROR',
        },
        'rabbitmq': {
            'level': 'INFO',
        },
        'gnm_deliverables.jwt_auth_backend': {
            'level': 'WARNING',
        },
        'gnm_deliverables': {
            'level': 'DEBUG',
        }
    },
    'root': {
        'handlers': ['console'], #the above loggers all take this
        'level': 'INFO',
    },
}

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    "gnm_deliverables.jwt_auth_backend.JwtAuth",
)

JWT_CERTIFICATE_PATH = os.environ.get("JWT_CERTIFICATE_PATH", os.path.join(BASE_DIR, "publiccert.pem"))
JWT_EXPECTED_AUDIENCE = os.environ.get('JWT_EXPECTED_AUDIENCE',
                                       ["master-realm", "account"])  # ["master-realm", "account"]
JWT_EXPECTED_ISSUER = os.environ.get("JWT_EXPECTED_ISSUER",
                                     "https://keycloak.local/auth/realms/master")

ARCHIVE_HUNTER_URL = os.environ.get("ARCHIVE_HUNTER_URL", "https://archive-hunter-root/")