import json

from messagebus import (
    AckMessage,
    Event,
    Message,
    MessageBus,
    NakMessage,
)
from messageprocessorutil import UuidMessageProcessor
from typing import Any

from services.interactor import DiscountAppliedInteractor
from services.model import DiscountAppliedRequest


class DiscountAppliedProcessor(UuidMessageProcessor):
    def __init__(
        self,
        discount_applied_interactor,    # type: DiscountAppliedInteractor
    ):
        # type: (...) -> None

        super(DiscountAppliedProcessor, self).__init__()
        self.discount_applied_interactor = discount_applied_interactor

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

        request_json = json.loads(data)

        return DiscountAppliedRequest(
            pos_id=request_json.get("posId"),
            order_id=request_json.get("orderId"),
        )

    def call_business(
        self,
        request,  # type: DiscountAppliedRequest
    ):
        # type: (...) -> None

        self.discount_applied_interactor.process_request(request)

    def format_response(
        self,
        message_bus,    # type: MessageBus
        message,        # type: Message
        event,          # type: Event
        request,        # type: DiscountAppliedRequest
        result,         # type: None
    ):
        # type: (...) -> None

        message_bus.reply_event(
            event=event,
            reply_message=AckMessage(data=result),
        )

    def format_parse_exception(
        self,
        message_bus,    # type: MessageBus
        message,        # type: Message
        event,          # type: Event
        data,           # type: Any
        exception,      # type: Exception
    ):
        # type: (...) -> None

        return None

    def format_exception(
        self,
        message_bus,    # type: MessageBus
        message,        # type: Message
        event,          # type: Event
        input_obj,      # type: DiscountAppliedRequest
        exception,      # type: Exception
    ):
        # type: (...) -> None

        message_bus.reply_event(
            event=event,
            reply_message=NakMessage(data=exception.message),
        )
