import pytest
from django.contrib.auth.models import User
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponseRedirect
from django.test import RequestFactory
from django.urls import reverse
from unittest.mock import patch

from core.middleware import LicenseMiddleware
from license_info.tests.test_tools import FULL_LICENSE


@pytest.mark.django_db
class TestMiddleware:

    def setup_class(self):
        """Prepare"""
        self.factory = RequestFactory()
        self.middleware = LicenseMiddleware(lambda x: x)

    @pytest.fixture
    def prepare_user(self):
        return User.objects.create_user("test_user", "name@name.com", "password")

    @pytest.fixture
    def prepare_request(self, prepare_user):
        def _inner(url):
            request = self.factory.get(reverse(url))
            request.user = prepare_user
            return request

        return _inner

    @pytest.fixture
    def process_request(self, prepare_user, prepare_request):
        """Send prepared request throw out middleware"""

        def _inner(url):
            return self.middleware(prepare_request(url))

        return _inner

    @pytest.mark.unit
    @patch("core.middleware.get_license_info")
    def test_has_license(self, mock_function, prepare_user, prepare_request, process_request):
        """Check that we have license in response from our middleware"""
        mock_function.return_value = FULL_LICENSE

        response = process_request("index")

        assert response.license == FULL_LICENSE

    # TODO: check how it is working now and fix this
    @pytest.mark.unit
    @patch("core.middleware.get_license_info")
    @pytest.mark.skip
    def test_has_no_license(self, mock_function, prepare_user, prepare_request, process_request):
        """Check that we have a redirect if no license found"""
        mock_function.return_value = None

        response = process_request("index")

        assert isinstance(response, HttpResponseRedirect)

    @pytest.mark.unit
    @patch("core.middleware.get_license_info")
    def test_has_no_license_activation(self, mock_function, prepare_user, prepare_request, process_request):
        """Check that we have a normal response if we call license URL and no license found"""
        mock_function.return_value = None

        response = process_request("license_activation")

        assert isinstance(response, WSGIRequest)
