<gh_stars>1-10
"""
Django settings for etldjango project.

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

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

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

from pathlib import Path
from os import path as pathdir
from decouple import config as env
import google.auth
import os
import io
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: don't run with debug turned on in production!
env_file = os.path.join(BASE_DIR.parent,  ".env")

if not os.path.isfile(env_file):
    import environ
    from google.cloud import secretmanager as sm
    SETTINGS_NAME = "application_settings_etl"
    _, project = google.auth.default()
    client = sm.SecretManagerServiceClient()
    name = f"projects/{project}/secrets/{SETTINGS_NAME}/versions/latest"
    payload = client.access_secret_version(
        name=name).payload.data.decode("UTF-8")
    env = environ.Env()
    env.read_env(io.StringIO(payload))
else:
    aut_file = env('KEY_JSON_FILE')
    GOOGLE_APPLICATION_CREDENTIALS = pathdir.join(BASE_DIR, aut_file)
    #os.environ["_PROXI"] = 'yes'
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = GOOGLE_APPLICATION_CREDENTIALS
    _, _ = google.auth.default()

try:
    IP_PROXI_EXT= env('_IP_PROXI_EXT')
except :
    IP_PROXI_EXT=None

DEBUG = bool(int(env('DEBUG')))
PROXI = 'no' if os.getenv('_PROXI') is None else os.getenv('_PROXI')  #env('_PROXI')
PORT_PROXI = env('_PORT_PROXI')
EMAIL_PROXI = env('_EMAIL_PROXI')

# Run proxiVPN
# sudo apt install openssh-server
# see: ps aux | grep ssh
# deleate: killall {number_proccess}
if PROXI == 'yes':
    with open('id_rsa', 'w') as f:
        f.write(env('_ID_RSA').replace('\\n', '\n'))
    os.system('sudo chmod 600 ./id_rsa && \
                sudo ssh -4 -i ./id_rsa -o StrictHostKeyChecking=no -D {} -C -N {} -f &'.format(
        PORT_PROXI, EMAIL_PROXI))

# API key json

aut_file = env('KEY_JSON_FILE')
KEY_MAPS_API = env('KEY_MAPS_API')
URL_OXIPERU2 = env('URL_OXIPERU2')
URL_OXIPERU2_DT = env('URL_OXIPERU2_DT')

# Project ID GCP
GCP_PROJECT_ID = env('GCP_PROJECT_ID')
# Bucket name
BUCKET_NAME = env('BUCKET_NAME')
BUCKET_ROOT = env('BUCKET_ROOT')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')
ALLOWED_HOSTS = ["*"]
CORS_ALLOW_ALL_ORIGINS = True


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'etldata',
    'rest_framework',
]
INSTALLED_APPS += ["storages"]

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

ROOT_URLCONF = 'etldjango.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 = 'etldjango.wsgi.application'


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

# DATABASES = {
#     # 'default': {
#     #     'ENGINE': 'django.db.backends.sqlite3',
#     #     'NAME': BASE_DIR / 'db.sqlite3',
#     # }
#     'default': {
#         'ENGINE': 'django.db.backends.postgresql_psycopg2',
#         'NAME': 'opencovidlocal',
#         'USER': 'postgres',
#         'PASSWORD': 'admin1234',
#         'HOST': '127.0.0.1',
#         'DATABASE_PORT': '5432',
#     }
# }

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': env('NAME'),
        'USER': env('USER_NAME'),
        'PASSWORD': env('PASSWORD'),
        'HOST': env('IP_SERVER'),
        'DATABASE_PORT': '5432',
        'TEST': {
            'NAME': 'mytestdatabase',
        },
    },
}


# Password validation
# https://docs.djangoproject.com/en/3.1/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.1/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/3.1/howto/static-files/

STORAGE_MODE = env('STORAGE_MODE')

# set storage based on STORAGE_MODE
if (STORAGE_MODE == 'local'):
    # storage mode for local development
    STATIC_URL = '/static/'
    STATIC_ROOT = '/tmp/static'

    DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
    STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

else:
    # storage mode for Google Cloud
    GS_BUCKET_NAME = env('GS_STATIC_BUCKET_NAME')

    STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_BUCKET_NAME)
    DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
    STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
    GS_DEFAULT_ACL = "publicRead"


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

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {'format': '%(levelname)s : %(message)s - [in %(pathname)s:%(lineno)d]'},
        'short': {'format': '%(message)s'}
    },
    'handlers': {
        'stackdriver': {
            'formatter': 'standard',
            'class': 'etldata.log_middleware.StackDriverHandler',
        },
    },
    'loggers': {
        'StackDriverHandler': {
            'handlers': ['stackdriver'],
            'level': "INFO"
        },
        'django.request': {
            'handlers': ['stackdriver']
        }
    },
}
