import json

from messagebus import (
    DefaultToken,
    DataType,
    Message,
    MessageBus,
    AckMessage,
    Event,
    InternalErrorMessage,
)
from application.interactor.totaled import GetTotaledMessageInteractor
from application.interactor.totaled.dto import GetTotaledMessageRequest
from application.model import TotaledMessage
from typing import Optional
from ._NoErrorProcessor import NoErrorProcessor


class GetTotaledMessageProcessor(NoErrorProcessor):
    def __init__(
        self,          # type: GetTotaledMessageProcessor
        interactor,    # type: GetTotaledMessageInteractor
    ):
        # type: (...) -> None

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

    def parse_data(
        self,          # type: GetTotaledMessageProcessor
        data,          # type: bytes
        event_type,    # type: str
    ):
        # type: (...) -> GetTotaledMessageRequest

        request_json = json.loads(data)

        return GetTotaledMessageRequest(
            pos_id=request_json.get("posId"),
            customer_id=request_json.get("customerId"),
        )

    def call_business(
        self,         # type: GetTotaledMessageProcessor
        request,      # type: GetTotaledMessageRequest
    ):
        # type: (...) -> TotaledMessage

        return self.interactor.get_totaled_message(request=request)

    def format_response(
        self,           # type: GetTotaledMessageProcessor
        message_bus,    # type: MessageBus
        message,        # type: Message
        event,          # type: Event
        request,        # type: str
        response,       # type: Optional[TotaledMessage]
    ):
        # type: (...) -> None

        totalization_message = {
            "en": "",
            "es": "",
            "pt": "",
        }
        if response is not None:
            totalization_message["en"] = response.totalization_message.en
            totalization_message["es"] = response.totalization_message.es
            totalization_message["pt"] = response.totalization_message.pt

        totaled_message = {"totalizationMessage": totalization_message}
        data = json.dumps(totaled_message).encode("utf-8")

        message_bus.reply_message(
            message=message,
            reply_message=AckMessage(
                data_type=DataType.json,
                data=data,
            )
        )
