"""
base settings to build other settings files upon.
"""

import environ
import os

ROOT_DIR = (
        environ.Path(__file__) - 3
)
APPS_DIR = ROOT_DIR.path("sndg")

env = environ.Env()

if os.path.exists(str(ROOT_DIR.path(".env"))):
    env.read_env(str(ROOT_DIR.path(".env")))

# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool("DJANGO_DEBUG", False)
# Local time zone. Choices are
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# though not all of them may be available with every OS.
# In Windows, this must be set to your system time zone.
TIME_ZONE = "UTC"
# https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True
# https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True
# https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
# https://docs.djangoproject.com/en/dev/ref/settings/#locale-paths
LOCALE_PATHS = [str(ROOT_DIR.path("locale"))]

# DATABASES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {"default": env.db("DATABASE_URL"),

             # 'mysql': { #postgresql
             # 'ENGINE': 'django.db.backends.mysql',
             # 'NAME': 'sndg5',
             # 'USER': 'root',
             # 'PASSWORD': 'mito',
             # }
             }
DATABASES["default"]["ATOMIC_REQUESTS"] = True

# URLS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = "config.urls"
# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = "config.wsgi.application"

# APPS
# ------------------------------------------------------------------------------
DJANGO_APPS = [
    "django.contrib.auth",
    'polymorphic',
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # "django.contrib.humanize", # Handy template tags
    "django.contrib.admin",
]
THIRD_PARTY_APPS = [
    "crispy_forms",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    'allauth.socialaccount.providers.google',
    # "rest_framework",
    # "django_celery_beat",

    'haystack',
    # 'django_neomodel',

    'tellme',

    # 'captcha',
    # 'crispy_forms',
    "resumable",
    'django_select2',

]

LOCAL_APPS = [
    "sndg.users.apps.UsersConfig",

    'bioseq',
    'pdbdb',
    # 'vardb',
    # 'chembl_model',
    'bioresources',
]
# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

# MIGRATIONS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#migration-modules
MIGRATION_MODULES = {"sites": "sndg.contrib.sites.migrations"}

# AUTHENTICATION
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#authentication-backends
AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model
AUTH_USER_MODEL = "users.User"
# https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url
LOGIN_REDIRECT_URL = "users:redirect"
# https://docs.djangoproject.com/en/dev/ref/settings/#login-url
LOGIN_URL = "account_login"

# PASSWORDS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers
PASSWORD_HASHERS = [
    # https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django
    "django.contrib.auth.hashers.Argon2PasswordHasher",
    "django.contrib.auth.hashers.PBKDF2PasswordHasher",
    "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
    "django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
]
# https://docs.djangoproject.com/en/dev/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"},
]

# MIDDLEWARE
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#middleware
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

# STATIC
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(env('STATIC_ROOT', default=ROOT_DIR("data/static")))
# https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = "/static/"
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = [str(APPS_DIR.path("static"))]
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

# MEDIA
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR("media"))
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = "/media/"

# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES = [
    {
        # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        # https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
        "DIRS": [str(APPS_DIR.path("templates"))],
        "OPTIONS": {
            # https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
            # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
            "loaders": [
                "django.template.loaders.filesystem.Loader",
                "django.template.loaders.app_directories.Loader",
            ],
            # https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.template.context_processors.i18n",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
                "django.template.context_processors.tz",
                "django.contrib.messages.context_processors.messages",
                "sndg.context_processors.config_variables",
            ],
        },
    }
]
# http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs
CRISPY_TEMPLATE_PACK = "bootstrap4"

# FIXTURES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#fixture-dirs
FIXTURE_DIRS = (str(APPS_DIR.path("fixtures")),)

# SECURITY
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-httponly
SESSION_COOKIE_HTTPONLY = True
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-httponly
CSRF_COOKIE_HTTPONLY = True
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-browser-xss-filter
SECURE_BROWSER_XSS_FILTER = True
# https://docs.djangoproject.com/en/dev/ref/settings/#x-frame-options
X_FRAME_OPTIONS = "DENY"

# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
    # "DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend"
    'DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend'
)

# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL.
ADMIN_URL = "admin_sndg/"
# https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = [("""Ezequiel Sosa""", "ezequieljsosa@gmail.com")]
# https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS

# LOGGING
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#logging
# See https://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "%(levelname)s %(asctime)s %(module)s "
                      "%(process)d %(thread)d %(message)s"
        }
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "verbose",
        }
    },
    "root": {"level": "INFO", "handlers": ["console"]},
}

# Celery
# ------------------------------------------------------------------------------
if USE_TZ:
    # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-timezone
    CELERY_TIMEZONE = TIME_ZONE
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-broker_url
CELERY_BROKER_URL = env("CELERY_BROKER_URL")
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_backend
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-accept_content
CELERY_ACCEPT_CONTENT = ["json"]
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-task_serializer
CELERY_TASK_SERIALIZER = "json"
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_serializer
CELERY_RESULT_SERIALIZER = "json"
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-time-limit
# TODO: set to whatever value is adequate in your circumstances
CELERY_TASK_TIME_LIMIT = 5 * 60
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-soft-time-limit
# TODO: set to whatever value is adequate in your circumstances
CELERY_TASK_SOFT_TIME_LIMIT = 60
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#beat-scheduler
CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
# django-allauth
# ------------------------------------------------------------------------------
ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True)
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_ADAPTER = "sndg.users.adapters.AccountAdapter"
# https://django-allauth.readthedocs.io/en/latest/configuration.html
SOCIALACCOUNT_ADAPTER = "sndg.users.adapters.SocialAccountAdapter"

# django-compressor
# ------------------------------------------------------------------------------
# https://django-compressor.readthedocs.io/en/latest/quickstart/#installation
INSTALLED_APPS += ["compressor"]
STATICFILES_FINDERS += ["compressor.finders.CompressorFinder"]
# Your stuff...
# ------------------------------------------------------------------------------

HAYSTACK_CONNECTIONS = {

    'default': {
        'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        'URL': env('SNDG_SOLR'),  # SNDG_SOLR=solr://127.0.0.1:8984/solr/Notes
        'INCLUDE_SPELLING': True,
        'EXCLUDED_INDEXES': ['bioresources.search_indexes.ResourceIndexOAI'],
    },

}
if "SNDG_OAI" in env:
    HAYSTACK_CONNECTIONS['oai'] = {
        'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        'URL': env('SNDG_OAI'),  # ex: 'http://127.0.0.1:8984/solr/oai'
        'INCLUDE_SPELLING': False,
        'EXCLUDED_INDEXES': ['bioresources.search_indexes.PublicationIndex',
                             'bioresources.search_indexes.StructureIndex',
                             'bioresources.search_indexes.AssemblyIndex',
                             'bioresources.search_indexes.ExpressionIndex',
                             'bioresources.search_indexes.ToolIndex',
                             'bioresources.search_indexes.BioProjectIndex',
                             'bioresources.search_indexes.PersonIndex',
                             'bioresources.search_indexes.OrganizationIndex',
                             'bioresources.search_indexes.ReadsArchiveIndex',
                             'bioresources.search_indexes.BarcodeIndex',
                             ],

    }

HAYSTACK_ID_FIELD = env("HAYSTACK_ID_FIELD", default='id')
HAYSTACK_DJANGO_CT_FIELD = env("HAYSTACK_DJANGO_CT_FIELD", default='django_ct')
HAYSTACK_DJANGO_ID_FIELD = env("HAYSTACK_DJANGO_ID_FIELD", default='django_id')
HAYSTACK_DOCUMENT_FIELD = env("HAYSTACK_DOCUMENT_FIELD", default='text')

CRISPY_TEMPLATE_PACK = 'bootstrap4'
FILE_UPLOAD_TEMP_DIR = "/tmp/sndg_tmp/"

OAIPMH_DOMAIN = "sndg.qb.fcen.uba.ar"
# LOCALE_PATHS = os.path.abspath(os.path.join(SITE_ROOT, "../locale")),

SNDG_JBROWSE = os.path.join(str(ROOT_DIR), env('SNDG_JBROWSE', default="data/jbrowse/data"))
STATICFILES_DIRS = [
    os.path.abspath(os.path.join(str(ROOT_DIR), "sndg/static/")),
    ("jbrowse", SNDG_JBROWSE),
]

BLASTDBSDIR = os.environ.get('BLASTDBSDIR', os.path.abspath(os.path.join(str(ROOT_DIR), "data/blastdbs/")))
JOBSDIR = os.environ.get('JOBSDIR', os.path.abspath(os.path.join(str(ROOT_DIR), "data/jobs/")))
NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:123@localhost:7687')
# NEOMODEL_SIGNALS = True
# NEOMODEL_FORCE_TIMEZONE = False
# NEOMODEL_ENCRYPTED_CONNECTION = True
# NEOMODEL_MAX_POOL_SIZE = 50

CACHES = {
    'default': env.cache('REDIS_URL'),
}

SCOPUS_API = os.environ.get('SCOPUS_API', os.path.join(str(ROOT_DIR), "data/scopus_api.json"))
PDBSDIR = "/data/databases/pdb/divided/"
PDBSENTRIES = "/data/databases/pdb/entries.idx"

# ACCOUNT_SIGNUP_FORM_CLASS = "sndg.users.forms.UserCreationForm"

# ACCOUNT_USERNAME_VALIDATORS = ['sndg.users.forms.Validator']

ACCOUNT_FORMS = {
    'signup': 'sndg.users.forms.UserCreationForm',
    'login': 'sndg.users.forms.CustomLoginForm'
}

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

LANGUAGE_CODE = 'es'
# https://docs.djangoproject.com/en/dev/ref/settings/#language-code
# LANGUAGE_CODE = "en-us"
LANGUAGES = (
    ('es', 'Español'),
    ('en', 'English'),
)
if "EMAIL_CONFIG" in env:
    EMAIL_CONFIG = env.email_url('EMAIL_CONFIG')
    vars().update(EMAIL_CONFIG)
TELLME_FEEDBACK_EMAIL = "sndg@qb.fcen.uba.ar"

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        }
    }
}
SOCIALACCOUNT_QUERY_EMAIL = True

GOOGLE_ANALYTICS_CODE = os.environ.get('GOOGLE_ANALYTICS_CODE', "")
FILE_UPLOAD_TEMP_DIR = os.environ.get('FILE_UPLOAD_TEMP_DIR', os.path.join(str(ROOT_DIR), "data/uploads/"))
DJANGO_SELECT2_I18N = 'ar'
MINCYT_URL = os.environ.get('MINCYT_URL', "")
MINCYT_API_URL = os.environ.get('MINCYT_API_URL', "http://datostest.sndg.mincyt.gob.ar/api")

SEQSTORE_DIR = env('SEQSTORE_DIR', default="data/seqs/")
SEQSTORE_DIR_TMP = env('SEQSTORE_DIR_TMP', default="data/tmp/seqs/")