import json
from typing import List

from messagebus import (
    AckMessage,
    InternalErrorMessage,
)
from messageprocessorutil import UuidMessageProcessor
from model import EventPublishDetail
from model.mapper import EventPublishDetailMapper
from model.repository import EventRepository


class GetPendingProcessor(UuidMessageProcessor):
    def __init__(self, event_repository: EventRepository):
        super().__init__()

        self.event_repository = event_repository

    def parse_data(self, **kwargs):
        return None

    def call_business(self, _):
        return self.event_repository.get_pending()

    def format_response(
        self,
        message_bus,
        message,
        event,
        input_obj,
        pending_events: List[EventPublishDetail],
    ):
        ret = []
        for pending in pending_events:
            ret.append(EventPublishDetailMapper.map(publish_detail=pending).to_dict())

        message_bus.reply_message(
            message=message,
            reply_message=AckMessage(
                data=json.dumps(ret).encode("utf-8")
            )
        )

    def format_exception(
        self,
        message_bus,
        message,
        event,
        input_obj,
        exception
    ):
        message_bus.reply_message(
            message=message,
            reply_message=InternalErrorMessage(ex=exception)
        )

    def format_parse_exception(
        self,
        message_bus,
        message,
        event,
        data,
        exception
    ):
        return self.format_exception(
            message_bus=message_bus,
            message=message,
            event=event,
            input_obj=data,
            exception=exception,
        )
