# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import random
import time

import grpc
from common.proto import dbscanserving_pb2 as dbscan
from common.proto import optical_attack_detector_pb2 as oad
from common.proto.context_pb2 import Empty
from common.proto.monitoring_pb2 import Kpi
from common.proto.optical_attack_detector_pb2_grpc import (
    OpticalAttackDetectorServiceServicer,
)
from common.proto.optical_attack_mitigator_pb2 import AttackDescription, AttackResponse
from common.rpc_method_wrapper.Decorator import (
    create_metrics,
    safe_and_metered_rpc_method,
)
from common.tools.timestamp.Converters import timestamp_utcnow_to_float
from dbscanserving.client.DbscanServingClient import DbscanServingClient
from monitoring.client.MonitoringClient import MonitoringClient
from opticalattackmitigator.client.OpticalAttackMitigatorClient import (
    OpticalAttackMitigatorClient,
)

LOGGER = logging.getLogger(__name__)

SERVICE_NAME = "OpticalAttackDetector"
METHOD_NAMES = ["DetectAttack"]
METRICS = create_metrics(SERVICE_NAME, METHOD_NAMES)

monitoring_client: MonitoringClient = MonitoringClient()
dbscanserving_client: DbscanServingClient = DbscanServingClient()
attack_mitigator_client: OpticalAttackMitigatorClient = OpticalAttackMitigatorClient()


class OpticalAttackDetectorServiceServicerImpl(OpticalAttackDetectorServiceServicer):
    def __init__(self):
        LOGGER.debug("Creating Servicer...")
        LOGGER.debug("Servicer Created")

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def DetectAttack(
        self, request: oad.DetectionRequest, context: grpc.ServicerContext
    ) -> Empty:

        if random.random() > 0.5:
            time.sleep(10)

        # run attack detection for every service
        detection_request: dbscan.DetectionRequest = dbscan.DetectionRequest()
        detection_request.num_samples = 310
        detection_request.num_features = 100
        detection_request.eps = 100.5
        detection_request.min_samples = 5
        for _ in range(200):
            grpc_sample = dbscan.Sample()
            for __ in range(100):
                grpc_sample.features.append(random.uniform(0.0, 10.0))
            detection_request.samples.append(grpc_sample)
        for _ in range(100):
            grpc_sample = dbscan.Sample()
            for __ in range(100):
                grpc_sample.features.append(random.uniform(50.0, 60.0))
            detection_request.samples.append(grpc_sample)
        for _ in range(10):
            grpc_sample = dbscan.Sample()
            for __ in range(100):
                grpc_sample.features.append(random.uniform(5000.0, 6000.0))
            detection_request.samples.append(grpc_sample)
        response: dbscan.DetectionResponse = dbscanserving_client.Detect(
            detection_request
        )

        # including KPI
        # TODO: set kpi_id and kpi_value according to the service
        kpi = Kpi()
        kpi.kpi_id.kpi_id.uuid = random.choice(["1", "2"])
        kpi.timestamp.timestamp = timestamp_utcnow_to_float()
        kpi.kpi_value.int32Val = random.choice(
            [-1, 0, 1]
        )  # response.cluster_indices[-1]
        monitoring_client.IncludeKpi(kpi)

        if -1 in response.cluster_indices:  # attack detected
            attack = AttackDescription()
            attack.cs_id.uuid = request.service_id.service_uuid.uuid
            response: AttackResponse = attack_mitigator_client.NotifyAttack(attack)

        # if attack is detected, run the attack mitigator
        return Empty()
