import json

from application.interactor.apply.apply_benefit import ApplyBenefitInteractor
from application.interactor.apply.apply_benefit.dto.request import ApplyBenefitRequest
from application.interactor.apply.dto import ApplyContext
from .._BaseApplyProcessor import BaseApplyProcessor


class ApplyBenefitProcessor(BaseApplyProcessor):

    def __init__(
        self,        # type: ApplyBenefitProcessor
        interactor,  # type: ApplyBenefitInteractor
    ):
        # type: (...) -> None

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

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

        parsed_data = json.loads(data)
        pos_id = int(parsed_data.get("posId"))
        originator_pos_id = int(parsed_data.get("originatorPosId") or pos_id)
        benefit = parsed_data["benefit"]
        user_auth_level = parsed_data.get("user_auth_level")
        if user_auth_level is None:
            user_auth_level = -1
        applier = parsed_data["applier"]

        return ApplyBenefitRequest(
            benefit=benefit,
            context=ApplyContext(
                pos_id=pos_id,
                originator_pos_id=originator_pos_id,
                user_auth_level=user_auth_level,
                applier=applier
            )
        )

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

        self.interactor.apply_benefit(apply_benefit_request=request)
