"""
Django settings for django_machina_project project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
import pathlib
from pathlib import Path
import sys
import traceback
SECURE_SSL_REDIRECT = False
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) #older
#BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
#print('base dir: ' + BASE_DIR)  #..../django_machina_project
PROJECT_PATH = pathlib.Path(__file__).parents[1]


#MACHINA OVERRIDE machina/conf/settings.py
# CALL BEFORE IMPORT MACHINA SETTINGS? IN ORDER TO OVERRIDE???
#This actually doesn't override for some reason:
MACHINA_FORUM_NAME = 'What Do White People Eat? Forums'
'''machina_settings.MACHINA_FORUM_NAME = 'bite'
machina_settings.FORUM_NAME = 'chicken2'
MACHINA_FORUM_NAME = machina_settings.MACHINA_FORUM_NAME'''
#FORUM_NAME = 'What Do White People Eat? Forums 2'
MACHINA_POST_CONTENT_MAX_LENGTH = 10000
MACHINA_PROFILE_AVATAR_MAX_UPLOAD_SIZE = 1000000


#from machina.conf import settings as machina_settings



#print ('machina_settings.ATTACHMENT_FILE_UPLOAD_TO')
#print(machina_settings.ATTACHMENT_FILE_UPLOAD_TO)
import mimetypes
mimetypes.add_type("text/css", ".css", True)
mimetypes.add_type("text/javascript", ".js", True)
#mimetypes.add_type("text/html", ".css", True)
mimetypes.add_type("text/html", ".html", True)
#from .base import * #??
#machina_example/example_project/project/settings/dev.py
'''example
#for x in pathlib.Path(__file__).parents:
#    print(x)

/Applications/MAMP/htdocs/venv/django_machina_project/django_machina_project
/Applications/MAMP/htdocs/venv/django_machina_project
/Applications/MAMP/htdocs/venv
/Applications/MAMP/htdocs
/Applications/MAMP
/Applications
/
'''

'''
machina main template directory:
/opt/homebrew/lib/python3.9/site-packages/machina/templates/machina
/opt/homebrew/lib/python3.9/site-packages/machina/static/machina/build
base dir: /Applications/MAMP/htdocs/venv/django_machina_project
'''
#machina
from machina import MACHINA_MAIN_TEMPLATE_DIR

#added
from machina import MACHINA_MAIN_STATIC_DIR


import django.views.static
#from django.urls.static import static

#/Applications/MAMP/htdocs/venv/django_machina_project/machina/templates/machina
#/Applications/MAMP/htdocs/venv/django_machina_project/machina/static/machina/build

# Quick-start development settings - unsuitable for production

# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
#SECRET_KEY = ''
# Read secret key from a file
with open(str(PROJECT_PATH / 's_key.txt')) as f:
    SECRET_KEY = f.read().strip()

''' example from https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment
#DEVELOPMENT ONLY
import os
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag')

'''

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

#if DEBUG == False:
#    THUMBNAIL_PREFIX = 'staticfiles/cache/'
#'localhost', 'whatdowhitepeopleeat.com', 'localhost:8001',
ALLOWED_HOSTS = ['py.whatdowhitepeopleeat.com','lifeandcheesecake.whatdowhitepeopleeat.com' 'dev.whatdowhitepeopleeat.com','208.167.253.118','whatdowhitepeopleeat.com:8000','www.whatdowhitepeopleeat.com','localhost', 'localhost:8000', 'localhost:8001', '127.0.0.1' , 'whatdowhitepeopleeat.com', 'ko-fi.com']
import logging
LOG_FILE = "/home/whatdowh/logs/djangomachina-errors.log"
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '{levelname} {asctime} {module} - {message}',
                'style': '{'
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
        'stream': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple',
        }
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
        },
        'sorl.thumbnail': {
                'handlers': ['stream', ],
                'level': 'DEBUG',
                'propagate': True
        }
    },
}
#TEST TEMP LOG

from django.http import JsonResponse

logger = logging.getLogger(__name__)

class CommonErrorMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response
    def process_exception(self, request, exception):
        if isinstance(exception, OperationalError):
            logger.error(f"OperationalError: {str(exception)}")
            return JsonResponse({'error': 'Service temporarily unavailable, try again later.'}, status=503)


try:
    with open(LOG_FILE, "a") as f:
        f.write("Starting WSGI\n")
        f.write("Python: " + sys.executable + "\n")
        f.write("Path: " + repr(sys.path) + "\n")
    sys.path.insert(0, "/home/whatdowh/django_machina_project")

    os.environ.setdefault(
        "DJANGO_SETTINGS_MODULE",
        "django_machina_project.settings"
    )

    #from django_machina_project.wsgi_production import application
    from django.core.wsgi import get_wsgi_application
    with open(LOG_FILE, "a") as f:
        f.write("WSGI application loaded\n")

except Exception:
    with open(LOG_FILE, "a") as f:
        traceback.print_exc(file=f)
    raise






# Application definition

INSTALLED_APPS = [
    #'django_machina_project',
    'whitenoise.runserver_nostatic',  # new
    'django.contrib.staticfiles',
    'django.contrib.sites',#new
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',

    # Machina dependencies:
    'mptt',
    'haystack',
    'widget_tweaks',

    # Machina apps:
    'machina',
    'machina.apps.forum',
    'machina.apps.forum_conversation',
    'machina.apps.forum_conversation.forum_attachments',
    'machina.apps.forum_conversation.forum_polls',
    'machina.apps.forum_feeds',
    'machina.apps.forum_moderation',
    'machina.apps.forum_search',
    'machina.apps.forum_tracking',
    'machina.apps.forum_member',
    'machina.apps.forum_permission',

    'machina_app',
    'pages',
    'sorl.thumbnail',
    "verify_email.apps.VerifyEmailConfig",
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware', #must be on top
    "whitenoise.middleware.WhiteNoiseMiddleware",  # new must be on top after 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',

    # Machina
    'machina.apps.forum_permission.middleware.ForumPermissionMiddleware',
]

ROOT_URLCONF = 'django_machina_project.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',
            ],
        },
    },
]
'''

print('TEMPLATES DIR: ' + str(PROJECT_PATH / 'templates'))
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': (
            # ...
            str(PROJECT_PATH / 'templates'),
            MACHINA_MAIN_TEMPLATE_DIR,
            str(PROJECT_PATH / 'templates/verify_email'),
            #[os.path.join(BASE_DIR, 'templates')],
            #str(PROJECT_PATH / 'pages' / 'templates'),
        ),
        #django.core.exceptions.ImproperlyConfigured: app_dirs must not be set when loaders is defined.
        #'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',

                # Machina
                'machina.core.context_processors.metadata',
            ],
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ]
        },
    },
]

#added  Machina settings that didn't exist
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    },
    'machina_attachments': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/tmp',
    },
}

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
    },
}
''' You can also decide to use a more powerfull backend such as Solr or Whoosh:

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': os.path.join(PROJECT_PATH, 'whoosh_index'),
    },
}'''

WSGI_APPLICATION = 'django_machina_project.wsgi.application'


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

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

if 'DATABASE_URL' in os.environ:
    DATABASES = {
        'default': dj_database_url.parse(os.environ.get('DATABASE_URL'))
    }
else:
    print("Postgres URL not found, using sqlite instead")
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

location = lambda x: os.path.join(
    os.path.dirname(os.path.realpath(__file__)), x)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
# other machina settings #
#STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"
#STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'  # new
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

print('MACHINA_MAIN_STATIC_DIR')
print(MACHINA_MAIN_STATIC_DIR)

STATIC_URL = '/static/'

#STATIC_URL = os.path.join(BASE_DIR, 'static')
#STATIC_ROOT = os.path.join(BASE_DIR,'static/')
#STATIC_ROOT = MACHINA_MAIN_STATIC_DIR # works partially to load just those files
#STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles/')
if DEBUG:
   STATIC_ROOT = STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
else:
   STATIC_ROOT = STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

print('STATIC_ROOT')
print(STATIC_ROOT)
#STATIC_ROOT = '/static'
#django_machina_project top folder
print ('STATIC_MAIN')
STATIC_MAIN = str(PROJECT_PATH / 'static/') #custom var

#print ( os.path.join(BASE_DIR,'static/') )
#STATIC_MAIN
print(STATIC_MAIN)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
#MACHINA_MAIN_STATIC_DIR
# /Applications/MAMP/htdocs/venv/django_machina_project/machina/static/machina/build

'''STATIC_MAIN,
str(os.path.join(BASE_DIR, "static/")),
'/machina_app/static/',
str(os.path.join(BASE_DIR, 'machina_app/static/')),
MACHINA_MAIN_STATIC_DIR,
#'machina/static/machina/build'
location("public/media"),
location("public/static"),
MACHINA_MAIN_STATIC_DIR + '/css/',
'/static/','''

print('CACHE DIR')
print (os.path.join(BASE_DIR, 'cache'))
print (os.path.join(BASE_DIR, 'cache/'))

# the rest is in the wsgi file in order to be displayed outside the /staticfiles
STATICFILES_DIRS = (
    STATIC_MAIN,
    #'machina_app/static',
    os.path.join(BASE_DIR, 'static'),
    MACHINA_MAIN_STATIC_DIR, #'/Applications/MAMP/htdocs/venv/django_machina_project/machina/static/machina/build'
    os.path.join(BASE_DIR, 'machina_app/static'),
    #BASE_DIR / "static",
    ####os.path.join(BASE_DIR, 'static'),
    #don'tuseos.path.join(BASE_DIR, 'staticfiles/cache'),
    #location("public/media"),
    #location("public/static"),
    #'/static',
    #os.path.join(BASE_DIR, machina_settings.ATTACHMENT_FILE_UPLOAD_TO),
    #'/cache',
    os.path.join(BASE_DIR, 'cache'),
    os.path.join(BASE_DIR, 'tmp'),
    #BASE_DIR + '/static/',

)

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
##MEDIA_ROOT = location("public/media")
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
#MEDIA_URL = '/media/'

# if you set this then directories like machina may add to url /machina/attachments/machina/attachments
#MEDIA_ROOT = os.path.join(BASE_DIR, "media")
#MEDIA_ROOT = machina_settings.ATTACHMENT_FILE_UPLOAD_TO

# People who get code error notifications. In the format
# [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')]
ADMINS = []
# URL of the admin page
ADMIN_URL = 'admin/'


MACHINA_FORUM_NAME = 'What Do White People Eat?'
MACHINA_POST_CONTENT_MAX_LENGTH = 10000
MACHINA_PROFILE_AVATAR_MAX_UPLOAD_SIZE = 1000000
#django settings

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

'''The maximum size in bytes that a request body may be before a SuspiciousOperation (RequestDataTooBig) is raised. The check is done when accessing request.body or request.POST and is calculated against the total request size excluding any file upload data. You can set this to None to disable the check. Applications that are expected to receive unusually large form posts should tune this setting.

The amount of request data is correlated to the amount of memory needed to process the request and populate the GET and POST dictionaries. Large requests could be used as a denial-of-service attack vector if left unchecked. Since web servers don’t typically perform deep request inspection, it’s not possible to perform a similar check at that level.
'''
DATA_UPLOAD_MAX_MEMORY_SIZE = 1021440 #2621440 is 2.5
#The maximum size (in bytes) that an upload will be before it gets streamed to the file system. See Managing files for details.
FILE_UPLOAD_MAX_MEMORY_SIZE = 1021440

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#EMAIL_HOST = 'chi111.greengeeks.com'
EMAIL_HOST = 'mail.phuc.technology'
EMAIL_PORT = 587 #465
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_ID')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PW')

DEFAULT_FROM_EMAIL = 'noreply@dojowayoflife.com'
EXPIRE_AFTER = "1d" # Will expire after one day from link generation
SUBJECT = 'DojoWayOfLife.com Email Verification'
