import json

from messagebus import Message
from typing import Optional
from update_api.dto import PosUpdaterDto

from ._BaseMessageProcessor import BaseUpdaterProcessor
from application.interactor import LoaderUpdaterInteractor
from application.util import settings


class LoaderUpdaterProcessor(BaseUpdaterProcessor):
    def __init__(
        self,           # type: LoaderUpdaterProcessor
        interactor,     # type: LoaderUpdaterInteractor
    ):
        # type: (...) -> None
        super(LoaderUpdaterProcessor, self).__init__()

        self.interactor = interactor

    def parse_data(
        self,       # type: LoaderUpdaterProcessor
        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: LoaderUpdaterProcessor
        data,   # type: Optional[PosUpdaterDto]
    ):
        # type: (...) -> Message

        settings.clear_status()
        return self.interactor.update_loaders(data=data)
