# -*- coding: utf-8 -*-
import json

import sysactions
from bustoken import TK_REMOTE_ORDER_VOID_REMOTE_ORDER
from custom_sysactions import user_authorized_to_execute_action
from msgbus import TK_SYS_NAK
from systools import sys_log_exception

from .. import mb_context


@sysactions.action
@user_authorized_to_execute_action
def do_void_remote_order(
    pos_id,     # type: str
    remote_id,  # type: str
):
    # type: (...) -> str

    return void_remote_order(
        pos_id=pos_id,
        remote_id=remote_id,
    )


def void_remote_order(
    pos_id,      # type: str
    remote_id,   # type: str
):
    # type: (...) -> str

    try:
        token = TK_REMOTE_ORDER_VOID_REMOTE_ORDER
        data = str(remote_id)
        timeout = 10000 * 1000
        msg = mb_context.MB_EasySendMessage('RemoteOrder', token, data=data, timeout=timeout)

        error_message = None
        if msg.token == TK_SYS_NAK:
            error_message = msg.data
            if not error_message:
                model = sysactions.get_model(pos_id)
                error_message = sysactions.translate_message(model, "UNKNOWN_ERROR")

        return error_message

    except Exception as _:
        sys_log_exception("Error voiding delivery order")
        raise
