# -*- coding: utf-8 -*-

import logging
import unicodedata

from typing import Dict, Any

from old_helper import validar_cnpj
from helper import remove_accents
from pos_model import Order, TenderType

from models import PosTenderToNfeTender, NfeTender, PosTenderBrandToNfeCardBrand
from _NfceXmlPartBuilder import NfceXmlPartBuilder

logger = logging.getLogger("FiscalWrapper")


class PagBuilder(NfceXmlPartBuilder):

    def __init__(self, versao_ws):
        # type: (int) -> None
        self.versao_ws = versao_ws

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

        if self.versao_ws not in (1, 3):
            xml = "<pag>"
        else:
            xml = ""
        for tender in order.tenders:
            tender_type = PosTenderToNfeTender.convert(tender.type)

            cnpj = validar_cnpj(tender.cnpj_auth)

            if tender.type in [TenderType.credit, TenderType.debit] and cnpj is False:
                tender_type = NfeTender.outros

            if self.versao_ws not in (1, 3):
                xml += "<detPag>"
            else:
                xml += "<pag>"

            if self.versao_ws in (1, 3):
                total_amount = tender.amount - tender.change
            else:
                total_amount = tender.amount

            xml += "<tPag>{:>02}</tPag>".format(tender_type)

            if tender_type == NfeTender.outros:
                tender_desc = tender.descr or tender.type
                xml += "<xPag>{}</xPag>".format(remove_accents(tender_desc))

            xml += "<vPag>{:>0.2f}</vPag>".format(total_amount)

            if tender_type in [NfeTender.cartao_credito, NfeTender.cartao_debito] and cnpj is not False:
                card_brand = PosTenderBrandToNfeCardBrand.convert(tender.bandeira)
                xml += "<card><tpIntegra>1</tpIntegra><CNPJ>{0}</CNPJ><tBand>{1}</tBand><cAut>{2}</cAut></card>" \
                    .format(tender.cnpj_auth.strip(), card_brand, tender.auth_code.strip())

            if self.versao_ws not in (1, 3):
                xml += "</detPag>"
            else:
                xml += "</pag>"

            if self.versao_ws not in (1, 3) and tender.change > 0.0:
                xml += "<vTroco>{:>0.2f}</vTroco>".format(tender.change)

        if self.versao_ws not in (1, 3):
            xml += "</pag>"

        return xml
