"""
Django settings for itsa_backend project.

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

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
import requests
import yaml
from os import path
import os
import sys 
import boto3
import tempfile 
import shutil
from dotenv import load_dotenv


basepath = path.dirname(__file__)
load_dotenv(path.abspath(path.join(basepath, '..', '.env')))
yaml_config_file_path = path.abspath(path.join(basepath, '..', 'constants.yaml'))

# load yaml config variables
with open (yaml_config_file_path) as f:
    configs = yaml.safe_load(f)

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# 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 = '-#3coh!qrs=)xpk-lwv_=2)kz))v3=irt*77%tj^ebx4rh(q=3'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

def get_ec2_hostname():
    if "test" in sys.argv[1]:
        return False
    try:
        ipconfig = 'http://169.254.169.254/latest/meta-data/local-ipv4'
        return requests.post(ipconfig, timeout=3).text
    except Exception:
        return False

ec2_ip = get_ec2_hostname()

ALLOWED_HOSTS = [
    'localhost',
    "127.0.0.1"
    # '*' this is bad, disable this if you can
    ]

# Please change this to allow health checks not to fail
try:
    ALLOWED_HOSTS.append(os.getenv('EB_DOMAIN'))
except:
    pass

if ec2_ip:
    ALLOWED_HOSTS.append(ec2_ip)

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'api',
    'corsheaders',
    'django_elastipymemcache'
]

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',
    'corsheaders.middleware.CorsMiddleware',   
]

CORS_ORIGIN_ALLOW_ALL = True

ROOT_URLCONF = 'itsa_backend.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 = 'itsa_backend.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',
#     }
# }

def get_user_creds(filePath):
    configs = {}
    with open(filePath) as fp:
        for (i, line) in enumerate(fp):
            details = line.strip()
            if (i == 0):
                configs['password'] = details
            else:
                configs['username'] = details
                break
    return configs

if not ec2_ip:
    DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': BASE_DIR / 'db.sqlite3',
            }
        }

else:
    rds_configs = configs['rds']

    # Connect to s3 bucket and download .pem to be uploaded to RDS configs, this is stored in s3 bucket
    # s3 = boto3.client('s3')

    # tmp_file_path = os.path.join('tmp', 'ca-cert')
    # os.mkdir(tmp_file_path)
    # ca_cert_file_name = os.path.join(tmp_file_path, 'rds-ca-2019.pem')

    # tmpdirpath = tempfile.mktemp()
    # s3_cert_file_path = f'{tmpdirpath}/rds-ca-2019-root.pem'
    # s3.download_file('elasticbeanstalk-ap-southeast-1-731706226892', 'rds-ca-2019-root.pem', ca_cert_file_name)

    print(">>> ENVIRONMENT VARIABLES" + str(os.environ))
    if 'RDS_HOSTNAME' in os.environ:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': os.environ['RDS_DB_NAME'],
                'USER': os.environ['RDS_USERNAME'],
                'PASSWORD': os.environ['RDS_PASSWORD'],
                'HOST': os.environ['RDS_HOSTNAME'],
                'PORT': os.environ['RDS_PORT'],
                # 'OPTIONS': {
                #     'ssl': {
                #         'ca': os.getcwd() + '/rds-ca-2019-root.pem'
                #     }
                # }
            }
        }
    else: 
        try:
            DATABASES = {
                'default': {
                    'ENGINE': 'django.db.backends.mysql',
                    'NAME': rds_configs['db-name'],
                    'USER': os.getenv('RDS_USER'),
                    'PASSWORD': os.getenv('RDS_PASSWORD'),
                    'HOST': os.getenv('RDS_HOST'),
                    'PORT': rds_configs['rds-port'],
                    # 'OPTIONS': {
                    #     'ssl': {
                    #         'ca': os.getcwd() + '/rds-ca-2019-root.pem'
                    #     }
                    # }
                }
            }
        except Exception as e:
            raise Exception("ENVIRONMENT VARS FAILEDDDD >>>>>" + str(os.environ))
    
    # CACHES = {
    # 'default': {
    #     'BACKEND': 'django_elastipymemcache.backend.ElastiPymemcache',
    #     'LOCATION': 'dbcache.zeq2ul.cfg.apse1.cache.amazonaws.com:11211',
    #     'OPTIONS': {
    #       'ignore_exc': True, # pymemcache Client params
    #       'ignore_cluster_errors': True, # ignore get cluster info error
    #     }
    # }
# }

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

CACHE_TTL = 60




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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Singapore'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

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