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

import json

from sysactions import action, get_model, get_posot, show_messagebox, close_asynch_dialog

from utilfunctions import compare_objects

from ..customer import Customer
from ..customer.customer_model import AddCustomerRequest

dialog_id = None
delivery_keys = [
    "ADDRESS_REFERENCE",
    "CITY",
    "COMPLEMENT",
    "NEIGHBORHOOD",
    "POSTAL_CODE",
    "STATE",
    "STREET_NAME",
    "STREET_NUMBER",
]


def insert_or_update_customer(
    pos_id,                # type: str
    customer_json,         # type: dict
    update_order=False,    # type: bool
):
    # type: (...) -> None

    model = get_model(pos_id)
    pos_ot = get_posot(model)

    customer_request = _create_customer_request(customer_json)
    if update_order:
        _update_order_custom_properties(
            address_data_load=customer_json,
            model=model,
            pos_id=pos_id,
            pos_ot=pos_ot,
        )

    if not customer_request.phone:
        return

    customer = Customer().get_customer(phone=customer_request.phone)
    if not customer:
        message = "$CUSTOMER_WILL_BE_INSERTED"
        confirmation = show_messagebox(
            posid=pos_id,
            message=message,
            timeout=720000,
            buttons="$OK|$CANCEL",
        )
        if confirmation == 1:
            return
        Customer().add_customer(add_customer_request=customer_request)
    else:
        same_customer = compare_objects(
            obj1=customer_request,
            obj2=_create_customer_request_to_compare(customer=json.loads(customer)),
        )
        if not same_customer:
            message = "$CUSTOMER_WILL_BE_UPDATED"
            confirmation = show_messagebox(
                posid=pos_id,
                message=message,
                timeout=720000,
                buttons="$YES|$NO",
            )
            if confirmation == 1:
                return
        Customer().update_customer(add_customer_request=customer_request)


def insert_customer_and_save_on_sale(
    pos_id,                    # type: str
    customer_json,             # type: dict
    create_new_order=False,    # type: bool
):
    # type: (...) -> None

    selected_option = customer_json.get('SELECTED_OPTION', None)
    if selected_option is not None:
        customer_json.pop('SELECTED_OPTION')

    insert_or_update_customer(
        pos_id=pos_id,
        customer_json=customer_json,
        update_order=not create_new_order,
    )

    if create_new_order and selected_option == 2:
        from posactions import doSale

        doSale(
            pos_id=pos_id,
            item_id="",
            sale_type="DELIVERY",
            delivery_info_already_asked=True,
        )
        model = get_model(posid=pos_id)
        pos_ot = get_posot(model=model)
        _update_order_custom_properties(
            address_data_load=customer_json,
            model=model,
            pos_id=pos_id,
            pos_ot=pos_ot,
        )


def _create_customer_request(address_data_load):
    add_customer_request = AddCustomerRequest(
            address_data_load["CUSTOMER_PHONE"],
            address_data_load["CUSTOMER_DOC"],
            address_data_load["CUSTOMER_NAME"],
            address_data_load["POSTAL_CODE"],
            address_data_load["STATE"],
            address_data_load["CITY"],
            address_data_load["STREET_NAME"],
            address_data_load["NEIGHBORHOOD"],
            address_data_load["STREET_NUMBER"],
            address_data_load["COMPLEMENT"],
            address_data_load["ADDRESS_REFERENCE"]
    )

    return add_customer_request


def _create_customer_request_to_compare(customer):
    add_customer_request = AddCustomerRequest(
            customer["phone"],
            customer["document"],
            customer["name"],
            customer["address"]["zip_code"],
            customer["address"]["state"],
            customer["address"]["city"],
            customer["address"]["street"],
            customer["address"]["neighborhood"],
            customer["address"]["number"],
            customer["address"]["complement"],
            customer["address"]["reference_point"]
    )
    return add_customer_request


@action
def zip_code_search(pos_id):
    global dialog_id
    dialog_id = show_messagebox(pos_id, "$SEARCHING_ZIP_CODE", buttons="", asynch=True, timeout=50000)


@action
def zip_code_search_finished(pos_id, error="false"):
    close_asynch_dialog(pos_id, dialog_id)
    if error == "true":
        show_messagebox(pos_id, "$ERROR_SEARCHING_ZIP_CODE", buttons="OK")


def _update_order_custom_properties(address_data_load, model, pos_id, pos_ot):
    for key, value in address_data_load.iteritems():
        if value in ("", "None", None):
            if model.find('.//OrderProperty[@key="{}"]'.format(key)) is not None:
                pos_ot.setOrderCustomProperty(key, 'clear')
        else:
            pos_ot.setOrderCustomProperty(key, value.encode('utf-8'))

    _update_order_properties(pos_id, pos_ot, model)


def _update_order_properties(pos_id, pos_ot, model):
    sale_type = model.find(".//Order").get("saleType")
    pos_ot.updateOrderProperties(pos_id, saletype=sale_type)


def has_delivery_info(
    pos_id,    # type: str
):
    # type: (...) -> bool

    model = get_model(posid=pos_id)
    order = model.find("CurrentOrder/Order")
    if order is None:
        return False

    for prop in order.findall('.//OrderProperty'):
        if prop.get('key') in delivery_keys:
            return True
    return False

