import json
from xml.etree import cElementTree as eTree

from application.repository.api import APIRepository
from .dto import UnlockVoucherRequest

from order_api import OrderService
from order_api.dto import CustomProperty
from ...model import ApplierSubTypes


class UnlockVoucherInteractor(object):
    def __init__(
        self,               # type: UnlockVoucherInteractor
        api_repository,     # type: APIRepository
    ):
        # type: (...) -> None

        self.api_repository = api_repository

    def unlock_benefit(
        self,           # type: UnlockVoucherInteractor
        request,        # type: UnlockVoucherRequest
    ):
        # type: (...) -> None

        if request.benefit.get("applierSubType") == ApplierSubTypes.LOYALTY:
            self._update_applied_loyalty_on_total(
                order_picture=eTree.XML(request.order_picture),
                benefit_id=request.benefit_id,
            )

        self.api_repository.unlock_benefit(
            benefit_id=request.benefit_id,
            benefit=request.benefit,
            order_picture=request.order_picture,
            table_picture=request.table_picture,
        )

    def _update_applied_loyalty_on_total(
        self,           # type: UnlockVoucherInteractor
        order_picture,  # type: eTree.Element
        benefit_id,     # type: str
    ):
        # type: (...) -> None

        prop = order_picture.find(".//OrderProperty[@key='LOYALTY_COUPONS_TO_APPLY_ON_TOTAL']")
        if prop is None:
            return

        loyalty_on_total = json.loads(prop.get("value") or "[]")
        new_loyalty_on_total = []
        for current_benefit_id in loyalty_on_total:
            if current_benefit_id != benefit_id:
                new_loyalty_on_total.append(current_benefit_id)

        OrderService(
            pos_id=int(order_picture.get("posId")),
            message_bus=self.api_repository.message_bus,
        ).set_order_custom_property(custom_property=CustomProperty(
            key="LOYALTY_COUPONS_TO_APPLY_ON_TOTAL",
            value=json.dumps(new_loyalty_on_total),
        ))
