from typing import (
    Any,
    Dict,
    Optional,
)
from xml.etree import cElementTree as eTree

from nreports.builders import DataBuilder
from nreports.utils import is_true
from nreports_api.shared import JSON


class CustomerCallCouponBuilder(DataBuilder):

    def build_data(
        self,
        data_to_build: Dict[str, JSON],
        **kwargs: Any,
    ) -> Dict[str, JSON]:

        pos_id = int(kwargs["posId"])
        order_xml = kwargs["orderPicture"]

        customer_call_type = self.constants.get("CUSTOMER_CALL_TYPE", "ORDER_ID").lower()
        call_id = self._get_coupon_call_id(
            data_to_build=data_to_build,
            order_xml=order_xml,
            customer_call_type=customer_call_type,
        )
        customer_call_message = self.constants.get("CUSTOMER_CALL_MESSAGE")
        if not customer_call_message:
            labels = ["$CALL_PANEL", "$YOU_WILL_BE_CALLED"]
            translated_labels = self.i18n_repository.translate_labels(
                pos_id=pos_id,
                labels=labels,
            )
            customer_call_message = f"{translated_labels['$CALL_PANEL']} - {translated_labels['$YOU_WILL_BE_CALLED']}"

        data_to_build["CUSTOMER_CALL_MESSAGE"] = customer_call_message
        data_to_build["CUSTOMER_CALL_ID"] = call_id

        customer_call_before_danfe = self.constants.get("CUSTOMER_CALL_DANFE_POSITION", "before").lower() == "before"
        data_to_build["CUSTOMER_CALL_BEFORE_DANFE"] = customer_call_before_danfe
        data_to_build["CUSTOMER_CALL_AFTER_DANFE"] = not customer_call_before_danfe

        return data_to_build

    @staticmethod
    def _get_coupon_call_id(
        data_to_build: Dict[str, JSON],
        order_xml: eTree.Element,
        customer_call_type: str,
    ) -> Optional[str]:

        call_by_order_id = customer_call_type == "order_id"
        call_by_page_number = customer_call_type == "page_number"
        call_by_customer_name = customer_call_type == "customer_name"

        if not any([call_by_order_id, call_by_page_number, call_by_customer_name]):
            return None

        if call_by_order_id:
            data_to_build["CUSTOMER_CALL_ID_BY_ORDER_ID"] = True
            return order_xml.get("orderId")[-3:]

        if call_by_page_number:
            data_to_build["CUSTOMER_CALL_ID_BY_PAGE_NUMBER"] = True
            pager_number = order_xml.find("CustomOrderProperties/OrderProperty[@key='PAGER_NUMBER']")
            if pager_number is not None:
                pager_number = pager_number.get("value")

            return pager_number

        if call_by_customer_name:
            data_to_build["CUSTOMER_CALL_ID_BY_CUSTOMER_NAME"] = True
            customer_name = order_xml.find("CustomOrderProperties/OrderProperty[@key='CUSTOMER_NAME']")
            if customer_name is not None:
                customer_name = customer_name.get("value")

            return customer_name[:32]

        return None
