from helper import remove_accents
from pos_model import Order, XmlTenderTypeFromPOSMapper, TenderType, OrderTender

from _SatXmlPartBuilder import SatXmlPartBuilder
from satbuilder import ContextKeys
from typing import Dict


class PgtoBuilder(SatXmlPartBuilder):
    def __init__(self, tenders_type):
        # type: (Dict) -> None

        self.tenders_type = tenders_type

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

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

                tenders_by_type[tipo] += tender.amount
                tenders_cad_mc[tipo] = self._get_cad_mc(tender)

            for tender_type in tenders_by_type:
                amount = tenders_by_type[tender_type]
                cad_mc = tenders_cad_mc[tender_type]
                xml += tag.format(tender_type, amount, cad_mc)

        xml += "</pgto>"

        return xml

    def _get_cad_mc(
            self,
            tender  # type: OrderTender
    ):
        # type: (...) -> str

        if tender.type in [TenderType.credit, TenderType.debit] and tender.accreditor_sat not in ['', None]:
            return str(tender.accreditor_sat)

        others = "999"
        tender_description = str(remove_accents(tender.descr)).upper()
        if tender_description in self.tenders_type:
            tender_type_data_base = self.tenders_type[tender_description]
            cad_mc = str(tender_type_data_base.get("cAdmC", ""))
            return cad_mc if cad_mc.strip() else others

        return others
