import copy, grpc, 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.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 centralizedattackdetector.proto.monitoring_pb2 import Kpi, KpiList
from centralizedattackdetector.Config import GRPC_SERVICE_PORT, GRPC_MAX_WORKERS, GRPC_GRACE_PERIOD
from centralizedattackdetector.client.CentralizedAttackDetectorClient import CentralizedAttackDetectorClient
from centralizedattackdetector.proto.context_pb2 import Empty
from centralizedattackdetector.proto.service_pb2 import Service
from centralizedattackdetector.service.CentralizedAttackDetectorService import CentralizedAttackDetectorService

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_attack_detector_service(database):
    _service = CentralizedAttackDetectorService(
        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_attack_detector_client(centralized_attack_detector_service):
    _client = CentralizedAttackDetectorClient(address='127.0.0.1', port=port)
    yield _client
    _client.close()

def test_notify_service_update(centralized_attack_detector_client: CentralizedAttackDetectorClient):
    service = Service()
    centralized_attack_detector_client.NotifyServiceUpdate(service)

def test_detect_attack(centralized_attack_detector_client: CentralizedAttackDetectorClient):
    request = Empty()
    centralized_attack_detector_client.DetectAttack(request)

def test_report_summarized_kpi(centralized_attack_detector_client: CentralizedAttackDetectorClient):
    kpi_list = KpiList()
    centralized_attack_detector_client.ReportSummarizedKpi(kpi_list)

def test_report_kpi(centralized_attack_detector_client: CentralizedAttackDetectorClient):
    kpi_list = KpiList()
    centralized_attack_detector_client.ReportKpi(kpi_list)
