# -*- coding: utf-8 -*-
import json
from xml.etree import cElementTree as eTree

import sysactions
from sysactions import (
    show_any_dialog,
    show_messagebox
)
from posot import OrderTaker

from .. import mb_context
from actions.delivery.confirm_delivery_payment import (
    set_order_tenders,
    confirm_delivery_payment_server
)


@sysactions.action
def delivery_arrangement_payment(
        pos_id,         # type:str
        order_id,       # type:str
        external_id     # type:str
):
    # type: (...) -> None

    try:

        order_take = OrderTaker(pos_id, mb_context)
        picture = order_take.orderPicture(orderid=order_id)
        order = eTree.XML(picture).find("Order")
        delivery_man = order.find(".//OrderProperty[@key='LOGISTIC_DELIVERYMAN_DATA']").get("value")

        order_gross = float(order.attrib["totalGross"])

        order_gross = "{0:.2f}".format(order_gross)
        delivery_man = "$DELIVERY_MAN_NAME_ARRANGEMENT|{}".format(delivery_man)
        order_value = "$ORDER_DELIVERY_VALUE|{}".format(order_gross)

        dialog_data = [delivery_man, order_value, "$ORDER_DELIVERY_PAYMENT"]

        buttons = "$OK|$CANCEL"
        dialog_type = "listWithInformation"
        title = "$DELIVERY_ARRANGEMENT"
        data_content = json.dumps({"linesMessage": dialog_data, "orderGross": order_gross})

        selected_option = show_any_dialog(
                pos_id,
                dialog_type,
                dialog_data,
                title,
                "",
                buttons,
                "",
                600000,
                "NOFILTER",
                "",
                "",
                "",
                data_content,
                False)

        if selected_option is None:
            return None

        if set_order_tenders(pos_id, order_id, None, order, order_take, selected_option):
            confirm_delivery_payment_server(order_id, pos_id, external_id)
            return

        show_messagebox(pos_id, "$ERROR_ON_CONFIRM_REMOTE_ORDER_DELIVERY", timeout=720000, buttons="$OK")
    except Exception as _:
        show_messagebox(pos_id, "$ERROR_ON_CONFIRM_REMOTE_ORDER_DELIVERY", timeout=720000, buttons="$OK")
