# coding=utf-8
import json
import os

import cfgtools
import sysactions

from bustoken import TK_REMOTE_ORDER_GET_LOGISTIC_PARTNERS, TK_REMOTE_ORDER_SEARCH_LOGISTIC
from msgbus import TK_SYS_ACK
from sysactions import action, show_listbox, translate_message, StopAction, show_messagebox, get_model

from .. import logger, mb_context
from application.interactor import UserInteractor
from model.customexception import LogisticPartnerNotFound, LogisticSearchError

logistic_partners = {}


@action
def select_logistic_partner(pos_id, order_id):
    # type: (str, str) -> None

    select_partner = _ask_for_logistic_partner(pos_id)
    if select_partner:
        _search_logistic_partner(order_id, pos_id, select_partner)


def _search_logistic_partner(order_id, pos_id, select_partner):
    params = [str(select_partner["id"]), order_id]

    if _should_ask_for_deliveryman_name():
        if select_partner["id"] == 0:
            own_delivery_men = UserInteractor().get_own_delivery_men()
            if own_delivery_men:
                index = show_listbox(pos_id, own_delivery_men, message="$DELIVERYMEN")
                if index is None:
                    raise StopAction()

                deliveryman_data = own_delivery_men[index]
                params.append(deliveryman_data)
            else:
                deliveryman_data = sysactions.show_keyboard(pos_id, "$DELIVERY_MAN_NAME")
                if deliveryman_data is not None and deliveryman_data != "":
                    params.append(deliveryman_data)
                else:
                    show_messagebox(pos_id, "$INSERT_DELIVERY_MAN_NAME")
                    return

    data = json.dumps("\0".join(params))
    msg = mb_context.MB_EasySendMessage("RemoteOrder", TK_REMOTE_ORDER_SEARCH_LOGISTIC, data=data, timeout=10000000)
    if msg.token == TK_SYS_ACK:
        show_messagebox(pos_id, "$SEARCHING_LOGISTIC_PARTNER")
    else:
        raise LogisticSearchError()


def _ask_for_logistic_partner(
    pos_id,     # type: str
):
    # type: (...) -> int

    try:
        partners = _get_logistic_partners()
    except LogisticPartnerNotFound as _:
        show_messagebox(
            posid=pos_id,
            message="$LOGISTIC_NOT_FOUND",
        )
        raise StopAction()

    listbox_options = map(lambda p: p["name"], partners)
    index = show_listbox(pos_id, listbox_options, message="$DELIVERYMEN")
    if index is None:
        raise StopAction()

    select_partner = partners[index]
    return select_partner


def _get_logistic_partners():
    global logistic_partners

    if not logistic_partners:
        logger.debug("Getting Logistic Partners from Remote Order")
        msg = mb_context.MB_EasySendMessage("RemoteOrder", TK_REMOTE_ORDER_GET_LOGISTIC_PARTNERS, timeout=10000000)
        if msg.token == TK_SYS_ACK:
            logger.debug("Logistic Partners from Remote Order: {}".format(msg.data))
            logistic_partners = json.loads(msg.data)
        else:
            logger.debug("Error getting Logistic Partners from Remote Order")

    if not logistic_partners:
        raise LogisticPartnerNotFound()

    return logistic_partners


def _should_ask_for_deliveryman_name():
    config = cfgtools.read(os.environ["LOADERCFG"])
    value = config.find_value("Customizations.DeliveryConfigurations.AskForDeliveryManName", False)
    value = str(value).upper() == 'TRUE'
    return value
