from unittest.mock import MagicMock

import pytest
from pyramid.config import Configurator
from pyramid.testing import DummyRequest, setUp, tearDown

from workspaces.capability.schema import Capability


@pytest.fixture(scope="module")
def test_config() -> Configurator:
    """
    Returns a dummy Configurator object for testing purposes with set up and teardown

    :return: Dummy Configurator
    """
    request = DummyRequest()
    config = setUp(request=request)
    config.add_request_method(
        lambda lookup: MagicMock(),
        "capability_info",
        reify=True,
    )
    yield config
    tearDown()


@pytest.fixture(scope="module")
def request_null_capability() -> DummyRequest:
    """
    Returns a dummy request object with a mocked capability_info

    :return: DummyRequest with configured mock CapabilityInfo
    """

    class MockCapabilityInfo(MagicMock):
        capabilities = [
            Capability(
                name="null",
                steps="test",
                max_jobs=2,
            ),
            Capability(
                name="error",
                steps="error",
                max_jobs=-1,
            ),
        ]

        def edit_capability(
            self, name: str, steps: str = None, max_jobs: int = None, enabled: bool = None
        ) -> bool:
            if name == "error":
                # This is here to mimic the case where an update fails to happen
                return False
            for capability in self.capabilities:
                if name == capability.name:
                    if steps:
                        capability.steps = steps
                    if max_jobs:
                        capability.max_jobs = max_jobs
                    if enabled:
                        capability.enabled = enabled
                    return True
            return False

        def lookup_capability(self, capability_name: str):
            for capability in self.capabilities:
                if capability_name == capability.name:
                    return capability
            return None

        def save_entity(self, capability: Capability):
            self.capabilities.append(capability)

    request = DummyRequest(capability_info=MockCapabilityInfo())
    return request