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_posot,
)

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.Element]
):
    # type: (...) -> bool

    model = get_model(posid=pos_id)
    if order is None:
        order_taker = get_posot(model=model)
        order = eTree.XML(order_taker.orderPicture(posid=pos_id))

    total_gross = float(order.get("totalGross", "0.0"))
    tip_amount = float(order.get("tip", "0.0"))

    return check_can_fiscalize_order(
        pos_id=pos_id,
        total_gross=total_gross,
        tip_amount=tip_amount,
    )


def check_can_fiscalize_order(
    pos_id,        # type: str
    total_gross,   # type: float
    tip_amount,    # type: float
):
    # type: (...) -> bool

    try:
        FiscalWrapperInteractor().can_fiscalize_order(
            total_gross=total_gross,
            tip_amount=tip_amount,
        )
        return True
    except FiscalizationException as ex:
        logger.error(msg="Error check can fiscalize order", exc_info=ex)
        model = get_model(posid=pos_id)
        _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,
    )
