from xml.etree import cElementTree as eTree

from modelcommon.fiscalwrapper import FiscalizationException
from mw_helper import show_message_dialog
from typing import Optional

from sysactions import action, get_model, get_current_order

from custom_sysactions import user_must_be_logged
from . import get_error_fiscal_message
from .. import logger
from application.interactor import FiscalWrapperInteractor


@action
@user_must_be_logged
def check_can_fiscalize_order_action(
    pos_id,         # type: str
    order=None,     # type: Optional[eTree.XML]
):
    # type: (...) -> bool

    model = get_model(posid=pos_id)
    if order is None:
        order = get_current_order(model=model)

    try:
        FiscalWrapperInteractor().can_fiscalize_order(order=order)
        return True
    except FiscalizationException as ex:
        logger.exception(msg="Error check can fiscalize order", exc_info=ex)
        _show_message_error(
            ex=ex,
            model=model,
            pos_id=pos_id,
        )
        return False


def _show_message_error(
    ex,         # type: Exception
    model,      # type: Optional[eTree.XML]
    pos_id,     # type: str
):
    # type: (...) -> None

    message = get_error_fiscal_message(
        model=model,
        exception=ex,
    )
    show_message_dialog(
        pos_id=pos_id,
        title="$ERROR",
        message=message,
    )
