import json
from xml.etree import cElementTree as eTree

from application.model import NDiscountTokens
from application.model.repository.benefit_applier import DefaultBenefitApplierRepository
from messagebus import Message, DataType
from msgbus import TK_SYS_ACK


class NDiscountCouponApplierRepository(DefaultBenefitApplierRepository):

    def __init__(self, configs, message_bus):
        super(NDiscountCouponApplierRepository, self).__init__(configs, message_bus)

        self.benefits = None

    def check_coupon_id(
        self,       # type: NDiscountCouponApplierRepository
        pos_id,     # type: int
        coupon_id,  # type: str
    ):
        # type: (...) -> bool

        self._get_all_benefits_cache(pos_id)
        return self.benefits and coupon_id in self.benefits

    def get_benefit_and_lock(
        self,       # type: NDiscountCouponApplierRepository
        coupon_id,  # type: str
    ):
        # type: (...) -> None

        return self.benefits[coupon_id]

    def unlock_benefit(
        self,
        benefit_id,     # type: str
        pos_id,         # type: int
    ):
        # type: (...) -> None

        return

    def burn_benefit(
        self,
        benefit_id,     # type: str
        pos_id,         # type: int
    ):
        # type: (...) -> None

        return

    def get_benefit_info(self, data):
        # type: (str) -> None

        return

    def get_benefit_id_by_custom_property(self, order_picture):
        # type: (eTree) -> None

        return

    def _get_all_benefits_cache(self, pos_id):
        if self.benefits is None:
            data = json.dumps(dict(posId=pos_id))
            message = Message(NDiscountTokens.TK_NDISCOUNT_GET_BENEFITS, DataType.string, data)
            response = self.message_bus.send_message("nDiscount", message)
            if response.token == TK_SYS_ACK:
                benefits = json.loads(response.data)

                self.benefits = {}
                for benefit in benefits:
                    self.benefits[benefit.get("benefitId")] = benefit.get("benefitJson")

