from systools import sys_log_exception

from actions.config import must_print_delivery_coupon
from actions.printer import send_json_data_print
from api.nreports import get_nreports_service
from model.customexception import DeliveryCouponPrintError
from typing import Optional
from utilfunctions import get_custom_property_value


def print_delivery_coupon(
    pos_id,         # type: str
    order_id,       # type: str
):
    # type: (...) -> None

    if not must_print_delivery_coupon():
        return

    brand = get_custom_property_value(
        pos_id=pos_id,
        order_id=order_id,
        custom_property='BRAND'
    )

    _print_delivery_coupon_text(
        pos_id=pos_id,
        order_id=order_id,
        brand=brand,
    )


def reprint_delivery_coupons(
    pos_id,         # type: str
    order_id,       # type: str
):
    # type: (...) -> None

    _print_delivery_coupon_text(
        pos_id=pos_id,
        order_id=order_id,
    )


def _print_delivery_coupon_text(
    pos_id,         # type: str
    order_id,       # type: str
    brand=None,     # type: Optional[str]
):
    # type: (...) -> None

    try:
        print_data = get_nreports_service().delivery_coupon(
            pos_id=pos_id,
            order_id=order_id,
        )
        send_json_data_print(
            pos_id=pos_id,
            print_data=print_data,
            brand=brand,
        )
    except Exception:
        msg = "Error printing Delivery Coupon"
        sys_log_exception(message=msg)
        raise DeliveryCouponPrintError(msg)
