import json

from messagebus import (
    Event,
    MessageBus,
)
from typing import Any
from ._DefaultMessageProcessor import DefaultMessageProcessor
from ..interactor import RemoteLoaderUpdaterInteractor
from ..model import DispatchedEvents


class RemoteLoaderUpdaterProcessor(DefaultMessageProcessor):
    def __init__(
        self,           # type: RemoteLoaderUpdaterProcessor
        interactor,     # type: RemoteLoaderUpdaterInteractor
    ):
        # type: (...) -> None

        super(DefaultMessageProcessor, self).__init__()
        self.interactor = interactor

    def parse_data(
        self,           # type: RemoteLoaderUpdaterProcessor
        data,           # type: str
        event_type,     # type: str
    ):
        # type: (...) -> str

        json_data = json.loads(data)
        return json_data.get("externalUpdateId")

    def call_business(
        self,                   # type: RemoteLoaderUpdaterProcessor
        external_update_id,     # type: str
    ):
        # type: (...) -> Any

        return self.interactor.update_loaders(external_update_id=external_update_id)

    def format_response(
        self,           # type: RemoteLoaderUpdaterProcessor
        message_bus,    # type: MessageBus
        _,              # type: Any
        event,          # type: Event
        input_obj,      # type: Any
        __,             # type: Any
    ):
        # type: (...) -> None

        data = {
            "externalUpdateId": input_obj
        }
        reply_event = Event(
            subject=DispatchedEvents.EVT_POS_UPDATER_REMOTE_LOADER_UPDATE_ACK.value,
            data=json.dumps(data),
        )
        if event:
            message_bus.publish_event(event=reply_event)

    def format_exception(
        self,           # type: RemoteLoaderUpdaterProcessor
        message_bus,    # type: MessageBus
        _,              # type: Any
        event,          # type: Event
        input_obj,      # type: Any
        __,             # type: Any
    ):
        # type: (...) -> None

        return
