import json
import logging

from bustoken import TK_LOYALTY_GET_ENDPOINTS_CONFIG
from msgbus import (
    FM_PARAM,
    MBException,
    SE_NOTFOUND,
    TK_SYS_ACK,
)
from sysactions import send_message
from actions.models import LoyaltyEndpointsConfig

logger = logging.getLogger("PosActions")
loyalty_endpoints_config = None


def should_ask_loyalty_message_on_total():
    # type: (...) -> bool

    return _get_loyalty_message_config(ask_on="ask_totaled")


def should_ask_loyalty_on_payment():
    # type: (...) -> bool

    return _get_loyalty_message_config(ask_on="ask_payment")


def _get_loyalty_message_config(ask_on):
    # type: (...) -> bool

    global loyalty_endpoints_config

    if loyalty_endpoints_config is not None:
        return getattr(loyalty_endpoints_config, ask_on)

    try:
        logger.info("Start getting loyalty endpoints config")
        response = send_message(
            dest_name="Loyalty",
            token=TK_LOYALTY_GET_ENDPOINTS_CONFIG,
            format=FM_PARAM,
        )

        if response.token == TK_SYS_ACK:
            response_dict = json.loads(response.data)
            loyalty_endpoints_config = LoyaltyEndpointsConfig(
                ask_totaled=response_dict.get("AskTotaled"),
                ask_payment=response_dict.get("AskPayment"),
            )
        else:
            logger.info("TK_LOYALTY_GET_ENDPOINTS_CONFIG returned NAK")

        return getattr(loyalty_endpoints_config, ask_on)
    except MBException as ex:
        if ex.errorcode == SE_NOTFOUND:
            logger.info("Component Loyalty not alive")
            loyalty_endpoints_config = LoyaltyEndpointsConfig(
                ask_totaled=False,
                ask_payment=False,
            )
    except (Exception,):
        logger.exception("Error getting loyalty endpoint config")

    return False
