import load.projects.cloud.loadtesting.server.admin.proto.log_pb2 as log_pb2
import load.projects.cloud.loadtesting.server.admin.proto.log_pb2_grpc as log_pb2_grpc
from load.projects.cloud.loadtesting import events
from load.projects.cloud.loadtesting import logan


class LogServicer(log_pb2_grpc.LogServicer):
    def __init__(self, controller: logan.Controller):
        self._controller = controller

    def level_response(self, state: events.EventWithAutostop.State):
        return log_pb2.LevelResponse(
            current_level=str(logan.repr_level(self._controller.current_log_level)),
            permanent_log_level=str(logan.repr_level(self._controller.permanent_log_level)),
            seconds_to_reset_level=state.stop_in,
            error=str(state.error),
        )

    def local_logging_response(self, state: events.EventWithAutostop.State):
        return log_pb2.LocalLoggingResponse(
            status='ENABLED' if state.is_in_progress else 'DISABLED',
            disable_in=state.stop_in,
            error=str(state.error),
        )

    def SetLevel(self, request: log_pb2.SetLevelRequests, context):
        """
        grpcurl -plaintext -d '{"level": "DEBUG", "duration": 30}' localhost:50055 Log/SetLevel
        """
        level = logan.parse_level(request.level)
        return self.level_response(self._controller.set_level(level, request.duration or None))

    def GetLevel(self, request, context):
        """
        grpcurl -plaintext localhost:50055 Log/GetLevel
        """
        return self.level_response(self._controller.log_level_state())

    def ReSetLevel(self, request, context):
        """
        grpcurl -plaintext localhost:50055 Log/ReSetLevel
        """
        return self.level_response(self._controller.reset_level())

    def EnableLocalLogging(self, request, context):
        """
            grpcurl -plaintext -d '{"duration": 30}' localhost:50055 Log/EnableLocalLogging
        """
        return self.local_logging_response(self._controller.enable_local_logging(request.duration or None))

    def LocalLoggingState(self, request, context):
        """
            grpcurl -plaintext localhost:50055 Log/LocalLoggingState
        """
        return self.local_logging_response(self._controller.local_logging_state())

    def DisableLocalLogging(self, request, context):
        """
            grpcurl -plaintext localhost:50055 Log/DisableLocalLogging
        """
        return self.local_logging_response(self._controller.disable_local_logging())
