"""
Django settings for ebdjangos project.

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

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

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

import os
import json
from django.core.exceptions import ImproperlyConfigured

# 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')


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/


# 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)

# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = get_secret("SECRET_KEY")
SECRET_KEY = "kg&%v4_+c^t(20y5v*jv6$nh@7)pdd4ol#y%-mx96@rxk=(uhy"

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

ALLOWED_HOSTS = ['*','django-env.ap-northeast-2.elasticbeanstalk.com']

LOGIN_REDIRECT_URL = '/'

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'storages',
    'watcher',
]

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


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

if 'RDS_HOSTNAME' in os.environ:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'OPTIONS':{
                'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            },
            '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'],
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }


# Password validation
# https://docs.djangoproject.com/en/2.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/2.1/topics/i18n/

LANGUAGE_CODE = 'ko_kr'

TIME_ZONE = 'Asia/Seoul'

USE_I18N = True

USE_L10N = True

USE_TZ = False


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


if OFF:
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

    fileDirectory1=os.path.join(BASE_DIR, 'logs/log_seatInfo')
    fileDirectory2 =  os.path.join(BASE_DIR, 'logs/log')



else:

    # # AWS Access
    # AWS_ACCESS_KEY_ID = get_secret("AWS_ACCESS_KEY_ID")
    # AWS_SECRET_ACCESS_KEY = get_secret("AWS_SECRET_ACCESS_KEY")
    # AWS_STORAGE_BUCKET_NAME = get_secret("AWS_STORAGE_BUCKET_NAME")
    # AWS Access
    AWS_ACCESS_KEY_ID = "AKIAVSQQJD6R3XLY7EFT"
    AWS_SECRET_ACCESS_KEY = "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"
    AWS_STORAGE_BUCKET_NAME = "ebdjango-s3"

    # AWS Setting
    AWS_REGION = 'ap-northeast-2'
    AWS_QUERYSTRING_AUTH = False
    AWS_S3_HOST = 's3.%s.amazonaws.com' % AWS_REGION
    AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME

    # Static Setting
    AWS_LOCATION = 'static'
    STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION )
    STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'  # s3 storage

    #Media Setting
    PUBLIC_MEDIA_LOCATION = 'media'
    MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, PUBLIC_MEDIA_LOCATION)
    # DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'  # s3 storage
    DEFAULT_FILE_STORAGE = 'ebdjangos.storage_backends.MediaSeatStorage'  # s3 storage

    fileDirectory1 = "/var/log/app_logs/log_seatInfo.txt"
    fileDirectory2 = "/var/log/app_logs/django_debug.txt"


LOGGING = {
    'version': 1,
    # 기존의 로깅 설정을 비활성화 할 것인가?
    'disable_existing_loggers': False,

    # 포맷터
    # 로그 레코드는 최종적으로 텍스트로 표현됨
    # 이 텍스트의 포맷 형식 정의
    # 여러 포맷 정의 가능
    'formatters': {
        'format1': {
            'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s',
            'datefmt': '%d/%b/%Y %H:%M:%S'
        },
        'format2': {
            'format': '%(levelname)s %(message)s'
        },
    },

    # 핸들러
    # 로그 레코드로 무슨 작업을 할 것인지 정의
    # 여러 핸들러 정의 가능
    'handlers': {
        # 로그 파일을 만들어 텍스트로 로그레코드 저장
        'file_seatInfo': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': fileDirectory1,
            # 'filename': os.path.join(BASE_DIR, 'logs/log_seatInfo'),
            # 'filename': "/var/log/app_logs/log_seatInfo.txt",
            'formatter': 'format1',
            'maxBytes':1024*1024*10,
            'backupCount':5,

        },
        'file_watcher': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': fileDirectory2,
            # 'filename': os.path.join(BASE_DIR, 'logs/log'),
            # 'filename': "/var/log/app_logs/django_debug.txt",
            'formatter': 'format1',
            'maxBytes': 1024 * 1024 * 10,
            'backupCount': 5,

        },

        # 콘솔(터미널)에 출력
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'format2',
        }
    },

    # 로거
    # 로그 레코드 저장소
    # 로거를 이름별로 정의
    'loggers': {
        'seatInfo': {
            'handlers': ['file_seatInfo'],
            'level': 'INFO',
        },
        'watcher':{
            'handlers':['file_watcher'],
            'level':'DEBUG',
        }

    },

}