import logging, pytest
from google.protobuf.json_format import MessageToDict
from common.database.Factory import get_database, DatabaseEngineEnum
from common.database.api.Database import Database
from common.database.tests.script import populate_example
from common.tests.Assertions import validate_topology
from context.client.ContextClient import ContextClient
from context.proto.context_pb2 import Empty
from context.service.ContextService import ContextService
from context.Config import GRPC_SERVICE_PORT, GRPC_MAX_WORKERS, GRPC_GRACE_PERIOD

port = 10000 + GRPC_SERVICE_PORT # avoid first 1024 privileged ports to avoid evelating permissions for tests

LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)

@pytest.fixture(scope='session')
def database():
    _database = get_database(engine=DatabaseEngineEnum.INMEMORY)
    return _database

@pytest.fixture(scope='session')
def service(database : Database):
    _service = ContextService(
        database, port=port, max_workers=GRPC_MAX_WORKERS, grace_period=GRPC_GRACE_PERIOD)
    _service.start()
    yield _service
    _service.stop()

@pytest.fixture(scope='session')
def client(service):
    _client = ContextClient(address='127.0.0.1', port=port)
    yield _client
    _client.close()

def test_get_topology_empty(client : ContextClient, database : Database):
    database.clear_all()
    validate_topology(MessageToDict(
        client.GetTopology(Empty()),
        including_default_value_fields=True, preserving_proto_field_name=True,
        use_integers_for_enums=False))

def test_get_topology_completed(client : ContextClient, database : Database):
    populate_example(database)
    validate_topology(MessageToDict(
        client.GetTopology(Empty()),
        including_default_value_fields=True, preserving_proto_field_name=True,
        use_integers_for_enums=False))
