import json
import logging

from application.model import ApplierSubTypes
from application.repository.api import APIRepository
from typing import Optional

logger = logging.getLogger(__name__)


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

        self.api_repository = api_repository

    def get_loyalty_customer_info(
        self,                 # type: GetLoyaltyCustomerInfoInteractor
        loyalty_customer_id,  # type: str
    ):
        # type: (...) -> Optional[str]

        logger.info("Requesting customer loyaltySystemId")
        loyalty_info = self.api_repository.retrieve_loyalty_customer_info(loyalty_customer_id=loyalty_customer_id)
        logger.info("Retrieved customer loyalty data: {}".format(loyalty_info))
        loyalty_info = self._update_applier_type(customer_info=loyalty_info)
        return loyalty_info

    @staticmethod
    def _update_applier_type(
        customer_info,  # type: str
    ):
        # type: (...) -> str

        if not customer_info:
            return customer_info

        try:
            info = json.loads(customer_info)
            benefits = info.get("benefits", [])
            for benefit in benefits:
                benefit["applier"] = "Loyalty"
                benefit["applierSubType"] = ApplierSubTypes.LOYALTY

            return json.dumps(info)
        except ValueError:
            logger.error("Invalid JSON returned: {}".format(customer_info))
            return customer_info
