# coding: utf-8

import io
import logging

import _pytest
import pytest
from django.core.files.storage import default_storage
from django.core.management import call_command
from pkg_resources import resource_filename

from procu.api import models
from .utils.test import ClientExternal, ClientInternal, get_file_content

# Do not escape unicode characters
_pytest.python._escape_strings = lambda x: x

collect_ignore = ['setup.py']


@pytest.fixture(autouse=True)
def global_setup(settings):
    logging.disable(logging.CRITICAL)

    apps = list(settings.INSTALLED_APPS)
    apps.remove('django_pgaas')
    settings.INSTALLED_APPS = apps

    mws = list(settings.MIDDLEWARE)
    mws.remove('django_replicated.middleware.ReplicationMiddleware')
    settings.MIDDLEWARE = mws

    auth_backends = list(settings.AUTHENTICATION_BACKENDS)
    auth_backends.remove('procu.api.auth.TVMAuthBackend')
    settings.AUTHENTICATION_BACKENDS = auth_backends

    settings.DATABASE_ROUTERS = []
    settings.DATABASES.pop('slave', None)

    # Prevent switching to another language
    # (all fixtures are in Russian)
    settings.LANGUAGE_CODE = 'ru'
    settings.LANGUAGES = [('ru', 'Russian')]

    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

    settings.CACHES = {
        'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}
    }


@pytest.fixture()
def clients():
    return {'internal': ClientInternal(), 'external': ClientExternal()}


@pytest.fixture(scope='session')
def django_db_setup(django_db_setup, django_db_blocker):

    fixtures = (
        'suppliers',
        'users',
        'categories',
        'addresses',
        'legal_entities',
        'oracle',
        'enquiries',
        'requests',
        'attachments',
        'links',
        'formdata',
        'dashboards',
        'discounts',
        'currencies',
        'units',
        'supplier_tags',
        'enquirynotes',
        'enquiryaccesses',
        'enquirycomments',
        'quotes',
        'quotecomments',
        'supplierwarnings',
    )

    fixture_files = [
        resource_filename('procu', f'fixtures/{name}.json') for name in fixtures
    ]

    with django_db_blocker.unblock():
        call_command('loaddata', '-i', *fixture_files)
        call_command('permissions')
        call_command('bucket')

        qs = models.Attachment.objects.values_list('id', 'file')

        for file_id, filename in qs:
            fp = io.BytesIO(get_file_content(file_id))
            default_storage.save(name=filename, content=fp)
