import pytest
from assertpy import (
    assert_that,
    fail,
)
from local_hyper_visor import LocalHyperVisor

from msgbus import (
    MBContext,
    MBException,
    MBService,
    SE_NOTFOUND,
)


def test_does_not_find_not_registered_service(
    hv_address,
    hv_port,
):
    mb_context = MBContext(
        my_service=MBService(
            address="127.0.0.1",
            port=14580,
        ),
        name="Locator",
    )

    hv_service = MBService(
        address=hv_address,
        port=hv_port,
    )

    try:
        mb_context.MB_LocateService(
            hv_service=hv_service,
            service_name="a service",
        )
        fail("Must raise MBException")
    except MBException as ex:
        assert_that(ex.errorcode).is_equal_to(SE_NOTFOUND)

    mb_context.MB_Finalize()


def test_finds_a_registered_service(
    hv_address,
    hv_port,
):
    my_service = MBService(
        address="127.0.0.1",
        port=14580,
    )
    mb_context = MBContext(
        my_service=my_service,
        name="Locator",
    )

    hv_service = MBService(
        address=hv_address,
        port=hv_port,
    )

    service_name = "service_name"
    mb_context.MB_RegisterService(
        my_service=my_service,
        hv_service=hv_service,
        service_type="service_type",
        service_name=service_name,
    )
    located_service = mb_context.MB_LocateService(
        hv_service=hv_service,
        service_name=service_name,
    )
    assert_that(located_service.address).is_equal_to(my_service.address)
    assert_that(located_service.port).is_equal_to(my_service.port)

    mb_context.MB_Finalize()
