import json
import random

import pytest
from assertpy import assert_that
from msgbus import (
    MBContext,
    MBService,
    TK_SYS_ACK,
    TK_SYS_HEALTH_CHECK,
)


def test_local_service_locator(mb_context, hv_service):
    service_type = "ServiceType"
    service_name = "ServiceName"

    service_address = "127.0.0.1"
    service_port = random.randint(30000, 65535)
    comp_service = MBService(
        address=service_address,
        port=service_port,
    )
    mb_context.MB_RegisterService(
        my_service=comp_service,
        hv_service=hv_service,
        service_type=service_type,
        service_name=service_name,
    )

    service = mb_context.MB_LocateService(
        hv_service=hv_service,
        service_name=service_name,
    )
    assert_that(service.address).is_equal_to(service_address)
    assert_that(service.port).is_equal_to(service_port)


def test_health_check(mb_context, hv_service):
    reply = mb_context.MB_SendMessage(
        destination=hv_service,
        token=TK_SYS_HEALTH_CHECK,
    )

    assert_that(reply.token).is_equal_to(TK_SYS_ACK)
    reply_dict = json.loads(reply.data.decode())
    assert_that(reply_dict).is_equal_to({"status": "OK"})

@pytest.fixture
def mb_context():
    random_port = random.randint(30000, 65535)
    client_service = MBService("127.0.0.1", random_port)

    mb_context = MBContext(
        my_service=client_service,
        name="ServiceLocatorClient",
    )

    yield mb_context

    mb_context.MB_Finalize()
