import json

from typing import (
    Any,
    Optional,
)

from messageprocessorutil import UuidMessageProcessor

from application.interactor import CatalogUpdaterInteractor
from messagebus import DefaultToken, DataType, Message
from application.util import settings

from update_api.dto import PosUpdaterDto


class CatalogUpdaterProcessor(UuidMessageProcessor):
    def __init__(self, interactor):
        # type: (CatalogUpdaterInteractor) -> None

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

    def parse_data(
        self,       # type: CatalogUpdaterProcessor
        message,    # type: Message
    ):
        # type: (...) -> Optional[PosUpdaterDto]

        if message and message.data:
            data = json.loads(message.data)
            return PosUpdaterDto(
                pos_id=data.get("pos_id"),
                user_id=data.get("user_id"),
            )

        return None

    def call_business(
        self,   # type: CatalogUpdaterProcessor
        data,   # type: Optional[PosUpdaterDto]
    ):
        # type: (Any) -> None

        settings.clear_status()
        self.interactor.apply_update(data=data)

    def format_response(self, message_bus, message, _, __, response):
        if response:
            message_bus.reply_message(message, Message(DefaultToken.TK_SYS_ACK, DataType.param, response))

    def format_exception(self, message_bus, message, _, __, exception):
        reply_message = Message(DefaultToken.TK_SYS_NAK, DataType.param, str(type(exception).__name__))
        message_bus.reply_message(message, reply_message)

    def format_parse_exception(self, message_bus, message, _, __, exception):
        message_bus.reply_message(message, Message(DefaultToken.TK_SYS_NAK, DataType.param, str(exception)))
