import json

from logging import Logger
from xml.etree import cElementTree as eTree

from application.model.customexception import (
    BenefitIdNotFoundInAppliedOrderBenefitsException,
    OrderHasNotBenefitListException,
)


def get_applier_sub_type_from_order(
    benefit_id,     # type: str
    order_picture,  # type: str
    logger,         # type: Logger
):
    # type: (...) -> str

    try:
        order = eTree.XML(order_picture)
        order_id = order.get("orderId")
        benefit_list = order.find(".//CustomOrderProperties/OrderProperty[@key='BENEFIT_LIST']")
        if benefit_list is None:
            raise OrderHasNotBenefitListException(
                order_id=order_id,
            )

        benefit_list = json.loads(benefit_list.get("value"))
        benefits = json.loads(benefit_list.get("benefitList", "{}"))

        for benefit in benefits:
            benefit_info = benefit.get("benefit", {})
            if benefit_info.get("id") != benefit_id:
                continue

            applier_sub_type = benefit_info.get("applierSubType")
            if applier_sub_type:
                return applier_sub_type

            break

        raise BenefitIdNotFoundInAppliedOrderBenefitsException(
            order_id=order_id,
            benefit_id=benefit_id,
        )

    except Exception as ex:
        logger.exception("Error trying to get applier sub type for benefitId: {}".format(benefit_id))
        raise ex
