import json

from typing import Optional

from update_api.dto import ChromeUpdaterDto

from messagebus import Message

from ._BaseMessageProcessor import BaseUpdaterProcessor
from application.interactor import ChromeUpdaterInteractor


class ChromeUpdaterProcessor(BaseUpdaterProcessor):
    def __init__(
        self,
        interactor    # type: ChromeUpdaterInteractor
    ):
        # type: (...) -> None

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

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

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

        return None

    def call_business(
        self,    # type: ChromeUpdaterProcessor
        data,    # type: Optional[ChromeUpdaterDto]
    ):
        # type: (...) -> Message

        return self.interactor.update_chrome(
            validate=(data and data.validate_version),
            data=data,
        )
