from sysactions import show_messagebox
from typing import Optional

from actions.config import should_ask_loyalty_message_on_total
from actions.functions.do_back_from_total import do_back_from_total
from actions.loyalty import get_loyalty_totaled_message
from utilfunctions import get_custom_property_value


def check_loyalty_totaled_message(
    pos_id,         # type: str
    table_id=None,  # type: Optional[str]
):
    # type: (...) -> None

    if not should_ask_loyalty_message_on_total():
        return

    customer_id = get_custom_property_value(
        pos_id=pos_id,
        custom_property="LOYALTY_ID",
    )

    if not customer_id:
        return

    loyalty_totaled_message = get_loyalty_totaled_message(
        pos_id=pos_id,
        customer_id=customer_id,
    )

    if loyalty_totaled_message:
        response = show_messagebox(
            posid=pos_id,
            buttons="$GO_TO_PAYMENT|$KEEP_BUYING",
            title="$INFORMATION",
            message=loyalty_totaled_message,
        )
        if response is None or response == 1:
            if table_id:
                from table_actions import reopen_table
                reopen_table(
                    pos_id=pos_id,
                    table_id=table_id,
                )
                return

            do_back_from_total(pos_id=pos_id)
