"""
Django settings for Simtime project.

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

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
import json
from django.core.exceptions import ImproperlyConfigured
from datetime import timedelta

DEBUG = False
ALLOWED_HOSTS = ['*']

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

secret_file = os.path.join(BASE_DIR, 'secrets.json')

with open(secret_file) as f:
    secrets = json.loads(f.read())


def get_secret(setting, secrets=secrets):
    """비밀 변수를 가져오거나 명시적 예외를 반환한다."""
    try:
        return secrets[setting]
    except KeyError:
        error_msg = "Set the {} environment variable".format(setting)
        raise ImproperlyConfigured(error_msg)


# 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 = get_secret("SECRET_KEY")
# KAKAO_KEY = get_secret("KAKAO_KEY")

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

# Application definition

INSTALLED_APPS = [
    'rest_framework',
    'invitations',
    'accounts',
    # 'files', #practice용
    'storages',
    'imagekit',
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAuthenticated', ],
    'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework_simplejwt.authentication.JWTAuthentication', ],


}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=14),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': False,
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUTH_HEADER_TYPES': ('JWT',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
}

AUTH_USER_MODEL = "accounts.Account"
AUTH_USER_RELATIONSHIP_MODEL = "accounts.Relationship"


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_WHITELIST = [ 
    # 허용할 프론트엔드 도메인 추가 EX: 'http://localhost:3000', 
    'https://localhost:3000', 
    'https://127.0.0.1:3000', 
    'http://localhost:3000', 
    'http://127.0.0.1:3000',
]

INTERNAL_IPS = ('127.0.0.1')

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'simtime',
        'USER': get_secret("DB_DEV").get("USER"),
        'PASSWORD': get_secret("DB_DEV").get("PASSWORD"),
        'HOST': 'db-simtime.ck9ayn5ohacg.ap-northeast-2.rds.amazonaws.com'
    },

    'PROD': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'simtime',
        'USER': get_secret("DB_PROD").get("USER"),
        'PASSWORD': get_secret("DB_PROD").get("PASSWORD"),
        'HOST': 'db-simtime.ck9ayn5ohacg.ap-northeast-2.rds.amazonaws.com'
    }
}


# 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 = 'ko-kr'

TIME_ZONE = 'Asia/Seoul'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# S3
S3 = {
    "AWS_UPLOAD_BUCKET": get_secret("AWS_UPLOAD_BUCKET"),
    "AWS_UPLOAD_USERNAME": get_secret("AWS_UPLOAD_USERNAME"),
    "AWS_UPLOAD_GROUP": get_secret("AWS_UPLOAD_GROUP"),
    "AWS_UPLOAD_REGION": get_secret("AWS_UPLOAD_REGION"),
    "AWS_UPLOAD_ACCESS_KEY_ID": get_secret("AWS_UPLOAD_ACCESS_KEY_ID"),
    "AWS_UPLOAD_SECRET_KEY": get_secret("AWS_UPLOAD_SECRET_KEY"),
    "AWS_S3_SIGNATURE_VERSION": get_secret('AWS_S3_SIGNATURE_VERSION'),
}

AWS_DEFAULT_ACL = 'public-read'
AWS_QUERYSTRING_AUTH = False
AWS_S3_HOST = 's3.%s.amazonaws.com' % S3["AWS_UPLOAD_REGION"]
AWS_S3_CUSTOM_DOMAIN = '%s.s3.%s.amazonaws.com' % (
    S3["AWS_UPLOAD_BUCKET"], S3["AWS_UPLOAD_REGION"])


# AWS Access
AWS_ACCESS_KEY_ID = get_secret("AWS_UPLOAD_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = get_secret("AWS_UPLOAD_SECRET_KEY")
AWS_STORAGE_BUCKET_NAME = get_secret("AWS_UPLOAD_BUCKET")
AWS_LOCATION = "simtime"

STATIC_ROOT = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/'
STATIC_URL = '/static/'


STATICFILES_STORAGE = 'Simtime.storages.StaticStorage'
STATICFILES_LOCATION = 'static'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'Simtime', 'assets'),
]

MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/'
MEDIA_ROOT = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/'
DEFAULT_FILE_STORAGE = 'Simtime.storages.MediaStorage'
MEDIAFILES_LOCATION = 'media'
