from yandex.cloud.priv.loadtesting.v1 import resource_preset_service_pb2, resource_preset_service_pb2_grpc, \
    resource_preset_pb2

import grpc
from load.projects.cloud.loadtesting.config import DEFAULT_PAGE_SIZE
from load.projects.cloud.loadtesting.logan import lookup_logger
from load.projects.cloud.loadtesting.server.api.common import handler
from load.projects.cloud.loadtesting.server.pager import Pager


class PresetServicer(resource_preset_service_pb2_grpc.ResourcePresetServiceServicer):
    def __init__(self):
        self.logger = lookup_logger('Presets')

    class _Get(handler.BasePrivateHandler):
        _handler_name = 'Get'

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

            preset = db.preset.get(request.preset_id)
            if not preset:
                context.abort(grpc.StatusCode.NOT_FOUND,
                              f"Preset {request.preset_id} is not found")
            return _convert_to_proto(preset)

    def Get(self, request, context):
        return self._Get(self.logger).handle(request, context)

    class _List(handler.BasePrivateHandler):
        _handler_name = 'list'

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

            pager = Pager(request.page_token,
                          request.page_token or DEFAULT_PAGE_SIZE,
                          request.filter)
            presets = db.preset.list(
                offset=pager.offset,
                limit=pager.page_size,
            )
            pager.set_shift(len(presets))
            presets_list = []
            for preset in presets:
                presets_list.append(_convert_to_proto(preset))
            return resource_preset_service_pb2.ListResourcePresetsResponse(resource_presets=presets_list,
                                                                           next_page_token=pager.next_page_token)

    def List(self, request, context):
        return self._List(self.logger).handle(request, context)


def _convert_to_proto(preset):
    return resource_preset_pb2.ResourcePreset(
        preset_id=preset.id,
        name=preset.name,
        description=preset.description,
        cores=preset.cores,
        memory=preset.memory,
        disk_size=preset.disk_size)
