from pos_model import Order, XmlTenderTypeFromPOSMapper

from _SatXmlPartBuilder import SatXmlPartBuilder
from satbuilder import ContextKeys


class CfePagType(object):
    dinheiro = 1
    credito = 3
    debito = 4
    outros = 99


class PgtoBuilder(SatXmlPartBuilder):
    def build_xml(self, order, context):
        # type: (Order, ContextKeys) -> unicode

        xml = "<pgto>"
        # Pagamentos

        template = "<MP><cMP>{0:>02}</cMP><vMP>{1:>0.2f}</vMP><cAdmC>999</cAdmC></MP>"
        if len(order.tenders) <= 10:
            for tender in order.tenders:
                tipo = XmlTenderTypeFromPOSMapper.get(tender.type)
                xml += template.format(tipo, tender.amount)
        else:
            tenders_by_type = {}
            for tender in order.tenders:
                tipo = XmlTenderTypeFromPOSMapper.get(tender.type)
                if tipo not in tenders_by_type:
                    tenders_by_type[tipo] = 0
                tenders_by_type[tipo] += tender.amount

            for tender_type in tenders_by_type:
                xml += template.format(tender_type, tenders_by_type[tender_type])

        xml += "</pgto>"

        return xml
