import yandex.cloud.priv.loadtesting.agent.v1.trail_service_pb2 as messages
import yandex.cloud.priv.loadtesting.agent.v1.trail_service_pb2_grpc as trail_grpc

import grpc
from load.projects.cloud.loadtesting.logan import lookup_logger
from load.projects.cloud.loadtesting.server.api.common import utils, handler
from load.projects.cloud.loadtesting.server.publisher.trail import push_to_clickhouse


class Trailer(trail_grpc.TrailServiceServicer):
    def __init__(self):
        self.logger = lookup_logger('TrailPublic')

    class _Create(handler.BasePublicHandler):
        _handler_name = 'Create'

        def proceed(self):
            create_trail, job = utils.validate_request_job(
                self.request,
                self.context,
                self.db,
                self.user_token,
                self.request_id,
            )
            push_to_clickhouse(create_trail, job)
            return messages.CreateTrailResponse(code=0)

    def Create(self, create_trail: messages.CreateTrailRequest, context: grpc.ServicerContext):
        return self._Create(self.logger).handle(create_trail, context)
