import sysactions

from utilconfigurations import must_require_void_reason
from utils import get_void_reason_id, get_canceled_by
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

    auth_user = auth_data if auth_data is not None else None
    canceled_by = get_canceled_by(
        pos_id,
        model,
        auth_user
    )

    void_reason = None
    void_type = "VOID_LINE"
    if must_require_void_reason(void_type):
        void_reason = get_void_reason_id(
            pos_id=pos_id,
            void_type=void_type,
            authentication_user=canceled_by,
        )
        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=canceled_by,
            order_id=order_id
        )

    for line_number in line_numbers.split('|'):
        custom_properties = {}
        custom_properties.update(void_reason or "")
        if void_reason is None:
            custom_properties.update({"VOID_AUTH_USER": canceled_by})

        current_line_sale_lines = [x for x in sale_lines if x.get("lineNumber") == line_number]
        for current_line in current_line_sale_lines:
            item_type = current_line.get("itemType")
            if item_type == "OPTION":
                continue

            voided_qty = float(current_line.get("qty", 0))
            if item_type != "PRODUCT":
                voided_qty = voided_qty - float(current_line.get("defaultQty", 0))
            custom_properties.update({"VOID_QTY": str(voided_qty)})

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

    return True
