"""
Django settings for cms project.

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

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 sys
import environ
import dj_database_url

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
root = environ.Path(__file__) - 2
env = environ.Env()  # set default values and casting
environ.Env.read_env(env_file=root('.env'))  # reading .env 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('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG', default=False)

ENVIRONMENT = env('ENVIRONMENT', default='local')

if ENVIRONMENT == 'heroku':
    CSRF_COOKIE_SECURE = True
    SESSION_COOKIE_SECURE = True
    SECURE_SSL_REDIRECT = True
    ALLOWED_HOSTS = [ env('APP_HOST_NAME') ]
    CORS_ORIGIN_WHITELIST = (
        env('APP_HOST_NAME')
    )
    CSRF_TRUSTED_ORIGINS = (
        env('APP_HOST_NAME')
    )
    APP_SCOPE = env('APP_HOST_NAME').split('.')[0]
else:
    APP_SCOPE = env('APP_SCOPE', default='smartclock')

if DEBUG:
    INTERNAL_IPS = ['127.0.0.1']
    CORS_ORIGIN_WHITELIST = (
        'localhost:8080',
        '127.0.0.1:8000'
    )
    CSRF_TRUSTED_ORIGINS = (
        'localhost:8080',
        '127.0.0.1:8000'
    )


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'debug_toolbar',

    'storages',
    'rest_framework',
    'rest_framework.authtoken',
    'django_filters',
    'corsheaders',
    'apps.iot'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

ROOT_URLCONF = 'cms.urls'
LOGIN_URL = '/admin/login/'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'apps/iot/templates'), os.path.join(BASE_DIR, 'cms/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 = 'cms.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
if ENVIRONMENT == 'local':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
else:
    DATABASES = {
        'default': dj_database_url.config(conn_max_age=600, ssl_require=SECURE_SSL_REDIRECT)
    }

# 
# DATABASE_SCOPE = DATABASES['default']['NAME'].split('/')[-1]

# 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',
    },
]


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

LANGUAGE_CODE = 'en-us'
TIME_ZONE = env('TIME_ZONE', default='US/Pacific')
USE_I18N = True
USE_L10N = True
USE_TZ = True


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

STATIC_ROOT = env('STATIC_ROOT', default=os.path.join(PROJECT_ROOT, "static"))
MEDIA_ROOT = env("MEDIA_ROOT", default=os.path.join(BASE_DIR, 'uploads'))



AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
AWS_STATIC_LOCATION = '%s/%s/static'%(APP_SCOPE, ENVIRONMENT)
AWS_MEDIA_LOCATION = '%s/%s/media'%(APP_SCOPE, ENVIRONMENT)

if ENVIRONMENT == 'local':   
    STATIC_URL = '/static/'
    MEDIA_URL = '/uploads/'

    DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
    PRIVATE_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'    

else:

    STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)
    MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA_LOCATION)
    
    STATICFILES_STORAGE = 'cms.storage_backends.StaticStorage'
    DEFAULT_FILE_STORAGE = 'cms.storage_backends.PublicMediaStorage'
    PRIVATE_FILE_STORAGE = 'cms.storage_backends.PrivateMediaStorage'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'frontend', 'static'),
)

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication'
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ],
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
}

MQTT_USERNAME = env("MQTT_USERNAME", default=None)
MQTT_PASSWORD = env("MQTT_PASSWORD", default=None)
MQTT_HOST = env("MQTT_HOST", default=None)
MQTT_PORT = int(env("MQTT_PORT", default=1883))
MQTT_CLIENT_NAME = env("MQTT_CLIENT_NAME", default='iot-server-%s'%(APP_SCOPE))