import os
from pathlib import Path

import pytest
import pytest_asyncio
from channels.db import database_sync_to_async
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from rest_framework.test import APIClient

from core.utils import dtnow
from users.models import UserInfo
# noinspection PyUnresolvedReferences
from console.tests.test_utils import add_user_with_permissions, test_server, get_url
# noinspection PyUnresolvedReferences
from networkmap.tests.migration_fixtures import create_filter_test_data, create_elk_function_test_data


@pytest.fixture(scope='function')
def add_admin_user_migration():
    """ Fixture for adding admin user from 0003_add_admin_user migration """
    if not User.objects.filter(username='admin').exists():
        UserInfo.create_user(username='admin',
                             password=make_password('nimda'),
                             email='admin@example.com',
                             is_superuser=True,
                             is_staff=True,
                             expire_date=dtnow(days=700).date(),
                             comment='admin')


@pytest.fixture(scope='function')
def api_client():
    """ Fixture for creating api_client"""

    api_client = APIClient()
    return api_client


@pytest.fixture(autouse=True)
def remove_files_after_test_vector_config():
    TMP_DIR_VECTOR = '/tmp/vector'

    Path(TMP_DIR_VECTOR).mkdir(parents=True, exist_ok=True)
    yield
    files = os.listdir(TMP_DIR_VECTOR)
    for file in files:
        os.remove(os.path.join(TMP_DIR_VECTOR, file))


@pytest_asyncio.fixture
async def async_admin_user(django_user_model):
    return await database_sync_to_async(lambda: django_user_model.objects.get())()
