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

from common import (
    FiscalOrderTotals,
    MobileProductParser,
)
from nreports_api.shared import JSON
from .._BaseFiscalNfce import BaseFiscalNfce


class BaseFiscalCouponMobileNfce(BaseFiscalNfce):

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

        fiscal_xml = kwargs["fiscalXml"]

        fiscal_order_totals = FiscalOrderTotals(fiscal_xml=fiscal_xml)

        self._build_header(
            data_to_build=data_to_build,
            fiscal_xml=fiscal_xml,
        )

        self._build_body(
            data_to_build=data_to_build,
            fiscal_xml=fiscal_xml,
            fiscal_order_totals=fiscal_order_totals,
            products=self._get_item_products(fiscal_xml=fiscal_xml),
        )

        self._build_footer(
            data_to_build=data_to_build,
            fiscal_xml=fiscal_xml,
        )

        return data_to_build

    @staticmethod
    def _get_item_products(
        fiscal_xml: eTree.Element,
    ) -> List[Dict[str, str]]:

        item_products: List[Dict[str, str]] = []
        fiscal_products = fiscal_xml.findall(".//prod")
        product_params = ["cProd", "xProd", "qCom", "uCom", "vUnCom", "vProd"]
        for product in fiscal_products:
            product_item = MobileProductParser(
                product_xml=product,
                params=product_params,
            )

            item_products.append(
                {
                    "ITEM_PRODUCT_CODE": product_item.product_code,
                    "ITEM_PRODUCT_NAME": product_item.product_name,
                    "ITEM_PRODUCT_QUANTITY": product_item.product_qty,
                    "ITEM_PRODUCT_UNIT": product_item.product_unit.upper(),
                    "ITEM_PRODUCT_PRICE": product_item.product_price,
                    "ITEM_PRODUCT_TOTAL_PRICE": product_item.product_total_price,
                }
            )

        return item_products
