from typing import (
    Union,
    Optional,
)
from xml.etree import cElementTree as eTree

from sysactions import (
    show_print_preview,
    show_messagebox,
)

from actions.printer import send_json_data_print
from json_report_to_html import JSONReportParserToHtml


def print_preview_report(
    pos_id,               # type: Union[str, int]
    report_data,          # type: str
    preview=True,         # type: Optional[bool]
    order=None,           # type: Optional[eTree.Element]
    allow_printing=True,  # type: Optional[bool]
):
    # type: (...) -> bool

    if report_data is not None:
        if preview:
            report_preview = JSONReportParserToHtml().parse(report=report_data)
            result = show_print_preview(
                posid=pos_id,
                text_data=report_preview.encode("utf-8"),
                title="$PRINT_PREVIEW",
                buttons="$PRINT|$CLOSE" if allow_printing else "$CLOSE",
            )
            if result in (1, None) or not allow_printing:
                return False

        send_json_data_print(
            pos_id=pos_id,
            print_data=report_data,
            order=order,
        )
    elif report_data in [None, "", "{}", "[]"]:
        show_messagebox(
            posid=pos_id,
            message="$NO_REPORT_DATA",
            title="$ERROR",
        )
