import json

from application.interactor.apply.apply_coupon import ApplyCouponInteractor
from application.interactor.apply.apply_coupon.dto.request import ApplyCouponRequest
from application.interactor.apply.dto import ApplyContext
from .._BaseApplyProcessor import BaseApplyProcessor


class ApplyCouponProcessor(BaseApplyProcessor):

    def __init__(
        self,        # type: ApplyCouponProcessor
        interactor,  # type: ApplyCouponInteractor
    ):
        # type: (...) -> None

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

    def parse_data(
        self,        # type: ApplyCouponProcessor
        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)
        coupon_id = str(parsed_data["couponId"])
        user_auth_level = parsed_data.get("user_auth_level")
        if user_auth_level is None:
            user_auth_level = -1

        return ApplyCouponRequest(
            coupon_id=coupon_id,
            context=ApplyContext(
                pos_id=pos_id,
                originator_pos_id=originator_pos_id,
                user_auth_level=user_auth_level,
                applier=None,
            )
        )

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

        self.interactor.apply_coupon(apply_coupon_request=request)
