"""
Django settings for gmv project.

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

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

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

import os
import re

from django_sharding_library.settings_helpers import database_configs

from sharded_storage.sharding_functions import DivModBucketingStrategy


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


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3cl=3iwg2gka2gjc6j$!*5t3&2&37-onzrzbe*^ef6swp&(j#e'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_sharding',
    'rest_framework',

    'sharded_storage',
    'api',
]

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


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

SHARDING_SETTINGS = {
    'items_shard_group': {
        'big_shard_count': 2,
        'small_shard_count': 2,
        'small_shard_size': 100000,
    },
    'sets_shard_group': {
        'big_shard_count': 2,
        'small_shard_count': 2,
        'small_shard_size': 100000,
    },
}

sharded_databases = []
name_sub_regex = re.compile(r'_group$')
for shard_group, shard_group_settings in SHARDING_SETTINGS.items():
    for big_shard_idx in range(shard_group_settings['big_shard_count']):
        for small_shard_idx in range(shard_group_settings['small_shard_count']):
            shard_idx = big_shard_idx * shard_group_settings['small_shard_count'] + small_shard_idx
            shard_name = name_sub_regex.sub('_' + str(shard_idx + 1), shard_group)
            connection_environment_variable = shard_name.upper() + '_DATABASE_URL'
            connection_url = 'sqlite:///{}'.format(os.path.join(os.path.dirname(BASE_DIR), 'db', '{}.sqlite3'.format(shard_name)))
            sharded_databases.append({
                'shard_group': shard_group,
                'name': shard_name,
                'environment_variable': connection_environment_variable,
                'default_database_url': connection_url,
            })

DATABASES = database_configs(databases_dict={
    'unsharded_databases': [
        {
            'name': 'default',
            'environment_variable': 'DATABASE_URL',
            'default_database_url': 'sqlite:///{}'.format(os.path.join(BASE_DIR, 'db.sqlite3')),
        }
    ],
    'sharded_databases': sharded_databases,
})

DJANGO_SHARDING_SETTINGS = {
    'items_shard_group': {
        'SKIP_ADD_SHARDED_SIGNAL': True,
        'BUCKETING_STRATEGY': DivModBucketingStrategy(
            shard_group='items_shard_group',
            databases=DATABASES,
            big_shard_count=SHARDING_SETTINGS['items_shard_group']['big_shard_count'],
            small_shard_count=SHARDING_SETTINGS['items_shard_group']['small_shard_count'],
            small_shard_size=SHARDING_SETTINGS['items_shard_group']['small_shard_size'],
        ),
    },
    'sets_shard_group': {
        'SKIP_ADD_SHARDED_SIGNAL': True,
        'BUCKETING_STRATEGY': DivModBucketingStrategy(
            shard_group='sets_shard_group',
            databases=DATABASES,
            big_shard_count=SHARDING_SETTINGS['sets_shard_group']['big_shard_count'],
            small_shard_count=SHARDING_SETTINGS['sets_shard_group']['small_shard_count'],
            small_shard_size=SHARDING_SETTINGS['sets_shard_group']['small_shard_size'],
        ),
    },
}

# Most applications will not need additional routers but if you need your own then
# remember that order does matter. Read up on them here (link).
DATABASE_ROUTERS = ['django_sharding_library.router.ShardedRouter']

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

# REST Framework
# http://www.django-rest-framework.org/api-guide/settings/

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework.filters.OrderingFilter',
    ),
#    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',  # noqa: E122
    'PAGE_SIZE': 20,
}

try:
    from .local_settings import *  # noqa: F401,F403
except ImportError:  # noqa: E722,S110
    pass
