"""
Django settings for django_jacket project.

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

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/
"""

from pathlib import Path

from django.core.management.utils import get_random_secret_key

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# 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 = get_random_secret_key()

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

ALLOWED_HOSTS = ['*']



# Application definition
PROJECT_APPS = [
    'product',
]

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'Jacket_Shop.apps.JacketShopConfig',

    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'djoser',
] + PROJECT_APPS

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.CorsPostCsrfMiddleware",
    "corsheaders.middleware.CorsMiddleware",
]

ROOT_URLCONF = 'django_jacket.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        '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 = 'django_jacket.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',
    }
}


# 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


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

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

ALLOWED_CORS = {
    "type": ["http", "https"],
    "ip": ["localhost", "127.0.0.1"],
    "port": ["8080", "8081", "8000", "80"]
}

def shuffle_lists(*args):
    """
    shuffle list together as a list of tuples
    :param args: (list/tuple/set) 2 or more lists to shuffle together
    :return: list(tuples)

    example:
    *args = ["http", "https"], ["localhost"], ["8080", "8081"]
    return -> [('http', 'localhost', '8080'), ('http', 'localhost', '8081'), ('https', 'localhost', '8081'), ('https', 'localhost', '8080')]
    """
    if len(args) < 2:
        raise AttributeError("minimum two list/tuple/set as arguments")
    elif len(args) == 2:
        for l in args:
            if not isinstance(l, (list, tuple, set)):
                raise AttributeError("one of arguments is not list/tuple/set")
        new_list = list()
        for l1 in args[0]:
            for l2 in args[1]:
                if not isinstance(l1, tuple):
                    l1 = (l1,)
                if not isinstance(l2, tuple):
                    l2 = (l2,)
                tuple_of_those = (l1)+(l2)
                new_list.append(tuple_of_those)
        return new_list
    else:
        return shuffle_lists(args[0], shuffle_lists(*args[1:]))


SHUFFLED_ALLOWED_CORS = shuffle_lists(ALLOWED_CORS["type"], ALLOWED_CORS["ip"], ALLOWED_CORS["port"])

CORS_ORIGIN_WHITELIST = tuple(f"{type}://{ip}:{port}" for type, ip, port in SHUFFLED_ALLOWED_CORS)
print("CORS_ORIGIN_WHITELIST = ", CORS_ORIGIN_WHITELIST)


CORS_URLS_REGEX = r'^/api/.*$'

CORS_ORIGIN_ALLOW_ALL = True