from _NfceXmlPartBuilder import NfceXmlPartBuilder
from _ContextKeys import ContextKeys
from modelcommon.model import Store
from pos_model import Order
from typing import Any, Dict


class TranspBuilder(NfceXmlPartBuilder):
    def __init__(
            self,
            store_model     # type: Store
    ):
        #  type: (...) -> None

        self.store_model = store_model
        street_name = self.store_model.address_street
        street_number = self.store_model.address_number
        neighborhood = self.store_model.neighborhood
        self.address = "{0}, {1} - {2}".format(street_name, street_number, neighborhood)
        self.address = self.address[:60]

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

        delivery_partner = context[ContextKeys.delivery_partner]
        mod_freight = 9 if delivery_partner is None else 4
        shipping = ""
        if delivery_partner is not None:
            shipping = self._get_shipping()

        return "<transp><modFrete>{0}</modFrete>{1}</transp>".format(mod_freight, shipping)

    def _get_shipping(
            self
    ):
        # type: (...)-> unicode

        tag = "<transporta>{}</transporta>"
        shipping = "<CNPJ>{}</CNPJ>".format(self.store_model.cnpj)
        shipping += "<xNome>{}</xNome>".format(self.store_model.name[:60])
        shipping += "<IE>{}</IE>".format(self.store_model.state_registration)
        shipping += "<xEnder>{}</xEnder>".format(self.address[:60])
        shipping += "<xMun>{}</xMun>".format(self.store_model.city[:60])
        shipping += "<UF>{}</UF>".format(self.store_model.state)

        return tag.format(shipping)
