from typing import Optional

from sysactions import (
    print_text,
    get_poslist,
    generate_report,
)

from actions.config import must_print_delivery_coupon
from model.customexception import DeliveryCouponPrintError
from utilfunctions import (
    get_device_service,
    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:
        pos_list_param = ",".join(str(x) for x in get_poslist())
        params = "\0".join([pos_id, str(order_id), pos_list_param])
        report_text = generate_report("deliveryreport", params)
        current_printer = get_device_service(
            pos_id=pos_id,
            device_type="printer",
            brand=brand,
        )
        print_text(
            posid=pos_id,
            model=None,
            text=report_text,
            force_printer=current_printer,
        )
    except Exception as _:
        raise DeliveryCouponPrintError("Error printing Delivery Coupon")
