# -*- coding: utf-8 -*-

import logging

from sysactions import action, show_confirmation, show_messagebox, StopAction
from bustoken import (
    TK_REMOTE_ORDER_SEND_ORDER_TO_LOGISTIC,
    TK_REMOTE_ORDER_SEND_DELIVERY_MANUAL_ORDER_AUTOMATIC_LOGISTIC,
)
from msgbus import TK_SYS_ACK

from .. import mb_context

logger = logging.getLogger("PosActions")

@action
def send_logistic_remote_order(pos_id, order_id=""):
    confirmation = show_confirmation(pos_id, "$LOGISTIC_SEND_CONFIRMATION")
    if not confirmation:
        raise StopAction()

    data = pos_id + "\0" + order_id
    logistic_send_order_token = TK_REMOTE_ORDER_SEND_ORDER_TO_LOGISTIC
    msg = mb_context.MB_EasySendMessage("RemoteOrder", logistic_send_order_token, data=data, timeout=10000000)
    if msg.token == TK_SYS_ACK:
        show_messagebox(pos_id, "$LOGISTIC_SENT")
        return

    show_messagebox(pos_id, "$LOGISTIC_SENT_ERROR")


def send_delivery_manual_order_automatic_logistic(
    order_id,     # type: str
):
    # type: (...) -> None

    try:
        response = mb_context.MB_EasySendMessage(
            dest_name="RemoteOrder",
            token=TK_REMOTE_ORDER_SEND_DELIVERY_MANUAL_ORDER_AUTOMATIC_LOGISTIC,
            data=order_id,
            timeout=10000000,
        )

        if response.token != TK_SYS_ACK:
            logger.error("NAK send delivery manual order automatic logistic: {}".format(response.data))

    except Exception as _:
        logger.exception("Error send delivery manual order automatic logistic")

