import copy, grpc, logging, pytest
from src.centralizedcybersecurity.proto.monitoring_pb2 import Kpi, KpiList
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.api.context.Constants import DEFAULT_CONTEXT_ID, DEFAULT_TOPOLOGY_ID
from common.database.tests.script import populate_example
from common.tests.Assertions import validate_empty, validate_service, validate_service_id, \
    validate_service_list_is_empty, validate_service_list_is_not_empty
from centralizedcybersecurity.Config import GRPC_SERVICE_PORT, GRPC_MAX_WORKERS, GRPC_GRACE_PERIOD
from centralizedcybersecurity.client.CentralizedCybersecurityClient import CentralizedCybersecurityClient
from centralizedcybersecurity.proto.context_pb2 import Empty
from centralizedcybersecurity.proto.service_pb2 import Service
from centralizedcybersecurity.service.CentralizedCybersecurityService import CentralizedCybersecurityService

port = 10000 + GRPC_SERVICE_PORT # avoid privileged ports

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 centralized_cybersecurity_service(database):
    _service = CentralizedCybersecurityService(
        database, port=port, max_workers=GRPC_MAX_WORKERS, grace_period=GRPC_GRACE_PERIOD)
    _service.start()
    yield _service
    _service.stop()

@pytest.fixture(scope='session')
def centralized_cybersecurity_client(centralized_cybersecurity_service):
    _client = CentralizedCybersecurityClient(address='127.0.0.1', port=port)
    yield _client
    _client.close()

@pytest.fixture(scope='session')
def test_notify_service_update(centralized_cybersecurity_client: CentralizedCybersecurityClient):
    service = Service()
    centralized_cybersecurity_client.NotifyServiceUpdate(service)

@pytest.fixture(scope='session')
def test_detect_attack(centralized_cybersecurity_client: CentralizedCybersecurityClient):
    request = Empty()
    centralized_cybersecurity_client.DetectAttack(request)

@pytest.fixture(scope='session')
def test_report_summarized_kpi(centralized_cybersecurity_client: CentralizedCybersecurityClient):
    kpi_list = KpiList()
    centralized_cybersecurity_client.ReportSummarizedKpi(kpi_list)

@pytest.fixture(scope='session')
def test_report_kpi(centralized_cybersecurity_client: CentralizedCybersecurityClient):
    kpi_list = KpiList()
    centralized_cybersecurity_client.ReportKpi(kpi_list)
