import sysactions

from utilconfigurations import must_require_void_reason
from utils import get_void_reason_id
from custom_sysactions import user_authorized_to_execute_action
from manager.reports import justification_report


@sysactions.action
@user_authorized_to_execute_action
def do_void_lines(pos_id, line_numbers=None, auth_data=None):
    if not line_numbers:
        return False

    model = sysactions.get_model(pos_id)
    sysactions.check_current_order(pos_id, model=model)

    if not sysactions.can_void_line(model, line_numbers):
        sysactions.show_messagebox(pos_id, "$NEED_TO_HAVE_ITEM_TO_VOID")
        return False

    void_reason = None
    void_type = "VOID_LINE"
    operator = str(auth_data) if auth_data is not None else None
    if isinstance(auth_data, list):
        operator = auth_data[0]

    if must_require_void_reason(void_type):
        void_reason = get_void_reason_id(
            pos_id=pos_id,
            void_type=void_type,
            operator=operator,
        )
        if void_reason is None:
            return True

    pos_ot = sysactions.get_posot(model)
    order = model.find("CurrentOrder/Order")
    order_id = order.get("orderId")
    sale_lines = order.findall("SaleLine")

    pos_ot.voidLine(int(pos_id), line_numbers)

    if void_reason:
        justification_report(
            pos_id=pos_id,
            justification_type="VOID_LINE",
            justification=void_reason.get('VOID_REASON_DESCR'),
            authorized_by=operator,
        )

    if auth_data is not None or void_reason is not None:
        for line_number in line_numbers.split('|'):
            deleted_line = [x for x in sale_lines if x.get("lineNumber") == line_number and x.get("level") == "0"][0]
            custom_properties = {}
            if auth_data is not None:
                custom_properties.update({"VoidAuthUser": auth_data})

            if void_reason is not None:
                custom_properties.update({"VOID_QTY": deleted_line.get("qty")})
                custom_properties.update(void_reason)

            pos_ot.setOrderCustomProperties(
                custom_properties,
                orderid=order_id,
                linenumber=line_number,
                itemid=deleted_line.get("itemId"),
                level="0",
                partcode=deleted_line.get("partCode"),
            )

    return True
