import json
import logging

from bustoken import TK_LOYALTY_GET_TOTALED_MESSAGE
from msgbus import (
    FM_PARAM,
    TK_SYS_ACK,
)
from sysactions import send_message
from typing import Optional
from actions.models import (
    LoyaltyTranslatedMessage,
    LoyaltyTotaledMessage,
)
from actions.util import get_pos_language

logger = logging.getLogger("PosActions")


def get_loyalty_totaled_message(
    pos_id,         # type: str
    customer_id,    # type: str
):
    # type: (...) -> Optional[LoyaltyTotaledMessage]

    data = {
        "posId": pos_id,
        "customerId": customer_id,
    }

    try:
        logger.info("Start getting loyalty totaled message")
        response = send_message(
            dest_name="Loyalty",
            token=TK_LOYALTY_GET_TOTALED_MESSAGE,
            format=FM_PARAM,
            data=json.dumps(data),
        )
        if response.token == TK_SYS_ACK:
            response_data = json.loads(response.data)
            loyalty_translated_message = LoyaltyTranslatedMessage(
                pt=response_data.get("totalizationMessage").get("pt"),
                en=response_data.get("totalizationMessage").get("en"),
                es=response_data.get("totalizationMessage").get("es"),
            )
            language = get_pos_language(pos_id=pos_id)[0:2]
            loyalty_totaled_message = LoyaltyTotaledMessage(loyalty_translated_message=loyalty_translated_message)
            translated_message = getattr(loyalty_totaled_message.totalization_message, language)
            if translated_message:
                return translated_message
        logger.info("TK_LOYALTY_GET_TOTALED_MESSAGE returned NAK")
        return None
    except Exception as _:
        logger.exception("Error getting loyalty totaled message")
        return None
