import yandex.cloud.priv.loadtesting.agent.v1.tank_service_pb2 as messages
import yandex.cloud.priv.loadtesting.agent.v1.tank_service_pb2_grpc as tank_grpc

import grpc
from load.projects.cloud.loadtesting.db.tables.tank import ClientStatus
from load.projects.cloud.loadtesting.logan import lookup_logger
from load.projects.cloud.loadtesting.server.api.common import permissions, handler
from load.projects.cloud.loadtesting.server.api.common.utils import authorize


class Tanker(tank_grpc.TankServiceServicer):
    def __init__(self):
        self.logger = lookup_logger('TankPublic')

    class _ClaimStatus(handler.BasePublicHandler):
        _handler_name = 'ClaimStatus'

        def proceed(self):
            claim_status = self.request
            context = self.context
            db = self.db

            tank = db.tank.get_by_compute_instance_id(claim_status.compute_instance_id)
            if not tank:
                raise context.abort(grpc.StatusCode.NOT_FOUND,
                                    f'Compute instance {claim_status.compute_instance_id} is not found.')

            authorize(self.context, self.user_token, tank.folder_id, permissions.TESTS_RUN, self.request_id)

            db.tank.update_status(tank, ClientStatus(
                messages.ClaimTankStatusRequest.Status.Name(claim_status.status)
            ))

            return messages.ClaimTankStatusResponse(code=0)  # TODO: hardcoded, unclear code

    def ClaimStatus(self, claim_status: messages.ClaimTankStatusRequest, context: grpc.ServicerContext):
        return self._ClaimStatus(self.logger).handle(claim_status, context)
