from typing import (
    Any,
    Dict,
)

from model import FiscalType
from .._DataBuilder import DataBuilder
from .._Util import build_util_variables
from nreports.builders.fiscal_coupon import (
    FiscalCouponNfceBuilder,
    FiscalCouponSatBuilder,
)
from nreports.builders.end_of_sale.fiscal_coupon_mobile import (
    BaseFiscalCouponMobileNfce,
    BaseFiscalCouponMobileSat,
)
from nreports.utils import get_fiscal_type
from nreports_api.shared import JSON


class CanceledFiscalCouponBuilder(DataBuilder):

    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"])
        order_service = self.order_api_repository.get_order_service(pos_id=pos_id)
        kwargs["orderPicture"] = order_xml = order_service.get_order_picture(order_id=order_id)
        kwargs["fiscalXml"] = fiscal_xml = self.order_api_repository.get_fiscal_xml(
            pos_id=pos_id,
            order_id=order_id,
            order_xml=order_xml,
        )
        data_to_build = build_util_variables(
            constants=self.constants,
            data_to_build=data_to_build,
            **kwargs,
        )

        is_mobile = str(kwargs.get("isMobile", "false")).lower() == "true"
        fiscal_type = get_fiscal_type(fiscal_xml=fiscal_xml)
        if fiscal_type == FiscalType.NFCE:
            builder = BaseFiscalCouponMobileNfce if is_mobile else FiscalCouponNfceBuilder
            data_to_build["NFCE_CANCELED_COUPON"] = True
            data_to_build["IS_NFCE"] = fiscal_type == FiscalType.NFCE
        else:
            builder = BaseFiscalCouponMobileSat if is_mobile else FiscalCouponSatBuilder
            data_to_build["SAT_CANCELED_COUPON"] = True
            data_to_build["IS_SAT"] = fiscal_type == FiscalType.SAT

        data_to_build = builder(*self.get_builder_init()).build_data(
            data_to_build=data_to_build,
            **kwargs,
        )

        return data_to_build
