from typing import Dict, Any
from pos_model import Order

from old_helper import validar_cnpj, validar_cpf

from _NfceXmlPartBuilder import NfceXmlPartBuilder
from _ContextKeys import ContextKeys


class DestinatarioBuilder(NfceXmlPartBuilder):

    def __init__(self, ambiente):
        # type: (unicode) -> None

        self.ambiente = ambiente

    def build_xml(self, order, context):
        # type: (Order, Dict[unicode, Any]) -> unicode

        # Dados Destinatario (cliente)
        xml = ""
        cpf_cnpj = order.customer_cpf
        context[ContextKeys.cpf_cnpj] = cpf_cnpj

        if cpf_cnpj:
            if len(cpf_cnpj) == 11 and validar_cpf(cpf_cnpj):
                xml += "<dest><CPF>{}</CPF>".format(cpf_cnpj)
            elif len(cpf_cnpj) == 14 and validar_cnpj(cpf_cnpj):
                xml += "<dest><CNPJ>{}</CNPJ>".format(cpf_cnpj)

            if not xml:
                return ""

            if self.ambiente == "2":
                xml += "<xNome>NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL</xNome>"

            if context[ContextKeys.delivery_partner] is not None:
                xml += self._get_address(context)

            xml += "<indIEDest>9</indIEDest>"
            xml += "</dest>"

        return xml

    @staticmethod
    def _get_address(
            context  # type: (Dict[unicode, Any])
    ):
        # type: (...) -> unicode

        delivery_partner = context[ContextKeys.delivery_partner]
        if delivery_partner is None:
            return ""

        delivery_address = delivery_partner.get("deliveryAddress")
        street_name = delivery_address.get("streetName")
        street_number = delivery_address.get("streetNumber")

        tag = "<enderDest>{0}</enderDest>"
        address = "<xLgr>{0}</xLgr><nro>{1}</nro>".format(street_name, street_number)
        complement = delivery_address.get("complement")
        if complement is not None:
            address += "<xCpl>{}</xCpl>".format(complement)

        address += "<xBairro>{}</xBairro>".format(delivery_address.get("neighborhood"))
        address += "<cMun>{}</cMun>".format(delivery_address.get("municipalityCode"))
        address += "<xMun>{}</xMun>".format(delivery_address.get("city"))
        address += "<UF>{}</UF>".format(delivery_address.get("state"))
        postal_code = delivery_address.get("postalCode", None)
        if postal_code is not None:
            address += "<CEP>{}</CEP>".format(postal_code)

        return tag.format(address)
