import logging
from typing import Iterator

import grpc
import structlog
from google.protobuf.empty_pb2 import Empty

from vision_filter.proto import filter_visualizer_pb2_grpc
from vision_filter.proto.ssl.detection.detection_pb2 import \
    Frame as DetectionFrame
# generated by protoc
from vision_filter.proto.ssl.field.geometry_pb2 import GeometryFieldSize

from .visualizer import Visualizer


class FilterVisualizer(filter_visualizer_pb2_grpc.FilterVisualizerServicer):
    def __init__(self, visualizer: Visualizer):
        self._log = structlog.get_logger()
        self._log.setLevel(logging.DEBUG)
        self._visualizer = visualizer

    def SetFieldGeometry(
        self, request: GeometryFieldSize, context: grpc.ServicerContext
    ) -> Empty:
        self._log.debug("SetFieldGeometry called", request=request, context=context)
        self._visualizer.set_field_geometry(request)
        return Empty()

    def GetFieldGeometry(
        self, request: Empty, context: grpc.ServicerContext
    ) -> GeometryFieldSize:
        self._log.debug("GetFieldGeometry called", request=request, context=context)
        return self._visualizer.get_field_geometry()

    def AddDetections(
        self, request_iterator: Iterator[DetectionFrame], context: grpc.ServicerContext
    ) -> Empty:
        self._log.debug("AddDetection called")
        for detection_frame in request_iterator:
            self._log.debug(
                "AddDetection received new frame", detection_frame=detection_frame
            )
            self._visualizer.add_detection(detection_frame)
        return Empty()
