import json

from sysactions import show_messagebox
from typing import (
    Dict,
    Optional,
    List,
)

import pyscripts

from msgbus import (
    FM_PARAM,
    TK_SYS_ACK,
    MBMessage,
)
from bustoken import TK_PROD_ORDER_PICKLIST


mb_context = pyscripts.mbcontext


def get_pick_list_orders(
    pos_id,             # type: str
    orders_list,        # type: List[str]
):
    # type: (...) -> Optional[Dict]

    try:
        data = {
            "posId": pos_id,
            "ordersList": orders_list,
        }

        response = _send_message(
            data=data,
        )

        if response.token == TK_SYS_ACK:
            return json.loads(
                s=response.data,
            )

    except Exception as ex:
        _show_error_message(
            pos_id=pos_id,
            message=ex.message,
        )

    return None


def print_pick_list_order(
    pos_id,             # type: str
    order_id,           # type: str
    printer_name,       # type: str
    selected_option,    # type: str
):
    # type: (...) -> bool

    try:
        data = {
            "posId": pos_id,
            "orderId": order_id,
            "selectedOption": selected_option,
            "printerName": printer_name,
        }
        response = _send_message(
            data=data,
        )
        if response.token != TK_SYS_ACK:
            _show_error_message(
                pos_id=pos_id,
                message=response.data,
            )
            return False

        return True
    except Exception as ex:
        _show_error_message(
            pos_id=pos_id,
            message=ex.message,
        )
        return False


def _send_message(
    data,   # type: Dict
):
    # type: (...) -> MBMessage

    data = json.dumps(
        obj=data,
    )

    return mb_context.MB_EasySendMessage(
        dest_name="ProductionSystem",
        token=TK_PROD_ORDER_PICKLIST,
        format=FM_PARAM,
        data=data,
        timeout=(10 * 1000000)
    )


def _show_error_message(
    pos_id,     # type: str
    message,    # type: str
):
    # type: (...) -> None

    message = "$ERROR_REPRINT_PICKLIST|{}".format(
        message
    )

    show_messagebox(
        posid=pos_id,
        message=message,
        title="$ERROR",
    )
