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

import iso8601
from common import FiscalOrderTotals
from nreports_api.shared import JSON
from ._BaseLoyaltyCoupon import BaseLoyaltyCoupon


class LoyaltyCouponNfceBuilder(BaseLoyaltyCoupon):

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

        pos_id = int(kwargs["posId"])
        order_id = int(kwargs["orderId"])
        fiscal_xml = kwargs["fiscalXml"]

        data_to_build["STORE_NAME"] = fiscal_xml.find(".//emit/xNome").text
        data_to_build["LOYALTY_QRCODE_URL"] = self._get_loyalty_qrcode_url(fiscal_xml=fiscal_xml)
        data_to_build["LOYALTY_PROTOCOL_DATE"] = self._get_protocol_date(fiscal_xml=fiscal_xml)

        self.fill_constant_values(
            pos_id=pos_id,
            order_id=order_id,
            data_to_build=data_to_build,
        )

        return data_to_build

    @staticmethod
    def _get_protocol_date(
        fiscal_xml: eTree.Element,
    ) -> str:

        protocol_date = iso8601.parse_date(fiscal_xml.find(".//dhEmi").text)

        return protocol_date.strftime("%d/%m/%Y %H:%M:%S")

    @staticmethod
    def _get_loyalty_qrcode_url(
        fiscal_xml: eTree.Element,
    ) -> str:

        fiscal_order_totals = FiscalOrderTotals(fiscal_xml=fiscal_xml)
        nfce_key = fiscal_xml.find(".//infNFe").attrib["Id"][3:]

        return f"{nfce_key}|{fiscal_order_totals.total_paid:.2f}"
