from pos_model import Order
from typing import (
    Dict,
    Any,
)

from _ContextKeys import ContextKeys
from _NfceXmlPartBuilder import NfceXmlPartBuilder
from common import InfAdicBuilderCommon
from ibpttaxprocessor import IbptTaxProcessor
from models import NfeTender
from services import TPagService


class InfAdicBuilder(NfceXmlPartBuilder):

    def __init__(
        self,                       # type: str
        customer_text_field,        # type: str
        tax_builder,                # type: IbptTaxProcessor
        coupon_fiscal_parameters,   # type: Dict[str, bool]
        tenders_type,               # type: Dict[str, Any]
    ):
        # type: (...) -> None

        self.customer_text_field = customer_text_field
        self.tax_builder = tax_builder
        self.coupon_fiscal_parameters = coupon_fiscal_parameters
        self.tenders_type = tenders_type

    def build_xml(
        self,       # type: InfAdicBuilder
        order,      # type: Order
        context,    # type: ContextKeys
    ):
        # type: (...) -> unicode

        inf_adic_builder_common = InfAdicBuilderCommon(
            order=order,
            customer_text_field=self.customer_text_field,
            tax_builder=self.tax_builder,
            coupon_fiscal_parameters=self.coupon_fiscal_parameters,
        )

        return u"<infAdic><infCpl>{0}</infCpl>{1}</infAdic>".format(
            inf_adic_builder_common.get_inf_cpl(),
            self._get_tenders_additional_info(order=order),
        )

    def _get_tenders_additional_info(
        self,     # type: InfAdicBuilder
        order,    # type: Order
    ):
        # type: (...) -> unicode

        xml = u""
        is_static_pix_already_added = False
        t_pag_service = TPagService(tenders_type=self.tenders_type)
        for tender in order.tenders:
            t_pag = t_pag_service.get_t_pag(tender=tender)
            if t_pag == NfeTender.pix_estatico and not is_static_pix_already_added:
                xml += u"""<obsCont xCampo="tPix"><xTexto>1</xTexto></obsCont>"""
                is_static_pix_already_added = True
            elif t_pag == NfeTender.pagamento_instantaneo_pix:
                xml += u"""<obsCont xCampo="tPix"><xTexto>0</xTexto></obsCont>"""
                xml += u"""<obsCont xCampo="idPIX"><xTexto>{}</xTexto></obsCont>""".format(
                    tender.nsu_host or tender.auth_code
                )

        return xml
