# -*- coding: utf-8 -*-
import json
import logging
from typing import Optional

from sysactions import (
    action,
    show_any_dialog,
    show_messagebox,
    StopAction,
)

from actions.delivery.delivery_address_information import (
    insert_customer_and_save_on_sale,
    has_delivery_info,
)
from custom_sysactions import block_action_if_order_items_not_resolved

logger = logging.getLogger("PosActions")


@action
@block_action_if_order_items_not_resolved
def delivery_address(
    pos_id,             # type: str
    is_edit="false",    # type: Optional[str]
):
    # type: (...) -> bool

    from posactions import ask_customer_delivery_data

    is_edit = is_edit.lower() == "true"
    if is_edit:
        return request_and_save_delivery_address(pos_id=pos_id)

    if ask_customer_delivery_data == "onTotal" and not has_delivery_info(pos_id=pos_id):
        return request_and_save_delivery_address(pos_id=pos_id)
    return True


@action
def save_delivery_address(
    pos_id,                      # type: str
    is_edit="false",             # type: Optional[str]
    is_action="false",           # type: Optional[str]
    create_new_order="false",    # type: Optional[str]
):
    # type: (...) -> bool

    from posactions import ask_customer_delivery_data

    is_edit = is_edit.lower() == "true"
    is_action = is_action.lower() == "true"
    create_new_order = create_new_order.lower() == "true"

    if ask_customer_delivery_data == "onTotal" or is_action:
        return request_and_save_delivery_address(
            pos_id=pos_id,
            dialog_type="saveCustomerDeliveryAddress",
            create_new_order=create_new_order,
        )
    if is_edit:
        return request_and_save_delivery_address(pos_id=pos_id)
    return True


def request_and_save_delivery_address(
    pos_id,                           # type: str
    dialog_type="deliveryAddress",    # type: Optional[str]
    create_new_order=False,           # type: Optional[bool]
):
    # type: (...) -> bool

    try:
        customer = show_any_dialog(
            posid=pos_id,
            dlgtype=dialog_type,
            message="",
            title="",
            infotext="",
            buttons="",
            icon="",
            timeout=6000000,
            mask="",
            defvalue="",
            minvalue="",
            maxvalue="",
            contents="",
            asynch=False,
        )
        customer_json = json.loads(customer)

        if customer_json:
            selected_option = customer_json.get('SELECTED_OPTION', None)
            if selected_option is None:
                raise StopAction()

            insert_customer_and_save_on_sale(
                pos_id=pos_id,
                customer_json=customer_json,
                create_new_order=create_new_order,
            )

        return True
    except Exception as _:
        logger.exception("Error inserting or updating customer")
        show_messagebox(pos_id, message="$CUSTOMER_ERROR_ON_UPDATE")
        return False
