from old_helper import round_half_away_from_zero

from typing import Dict, Any
from pos_model import Order
from _NfceXmlPartBuilder import NfceXmlPartBuilder
from _ContextKeys import ContextKeys


class TotalBuilder(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
        v_prod = context[ContextKeys.total_prod]
        v_desc = 0
        v_other = 0
        for sale_line in order.sale_items:
            item_discount = float(sale_line.item_discount or 0)
            if item_discount > 0:
                v_desc += item_discount
            else:
                v_other += abs(item_discount)

        v_desc = round_half_away_from_zero(
            number=v_desc,
            precision=2,
        )
        v_other = round_half_away_from_zero(
            number=v_other,
            precision=2,
        )

        discount_value = float(order.discount_amount or 0)
        context[ContextKeys.v_nf] = v_nf = v_prod - discount_value

        total_icsm = context[ContextKeys.total_icms]
        total_pis = context[ContextKeys.total_pis]
        total_cofins = context[ContextKeys.total_cofins]
        v_tot_trib = total_icsm + total_pis + total_cofins

        xml = "<total><ICMSTot>"
        xml += "<vBC>{:.02f}</vBC>".format(context[ContextKeys.total_icms_vbc])
        xml += "<vICMS>{:.02f}</vICMS>".format(total_icsm)
        xml += "<vICMSDeson>{:.02f}</vICMSDeson>".format(context.get(ContextKeys.deson, 0))

        if self.versao_ws not in (1, 3):
            xml += "<vFCP>{:.02f}</vFCP>".format(context.get(ContextKeys.total_fcp, 0))

        xml += "<vBCST>0.00</vBCST><vST>0.00</vST>"

        if self.versao_ws not in (1, 3):
            xml += "<vFCPST>{:.02f}</vFCPST>".format(context.get(ContextKeys.total_fcp_st, 0))
            xml += "<vFCPSTRet>{:.02f}</vFCPSTRet>".format(context.get(ContextKeys.total_fcp_ant, 0))

        xml += "<vProd>{:.02f}</vProd>".format(v_prod)
        xml += "<vFrete>0.00</vFrete><vSeg>0.00</vSeg>"
        xml += "<vDesc>{:.02f}</vDesc>".format(v_desc)
        xml += "<vII>0.00</vII><vIPI>0.00</vIPI>"

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

        xml += "<vPIS>{:.02f}</vPIS>".format(total_pis)
        xml += "<vCOFINS>{:.02f}</vCOFINS>".format(total_cofins)
        xml += "<vOutro>{:.02f}</vOutro>".format(v_other)
        xml += "<vNF>{:.02f}</vNF>".format(v_nf)
        xml += "<vTotTrib>{:.02f}</vTotTrib>".format(v_tot_trib)
        xml += "</ICMSTot></total>"

        return xml
