from xml.etree import cElementTree as eTree

from common.builder_functions import optional
from helper import round_half_away_from_zero


class FiscalOrderTotals:

    def __init__(
        self,
        fiscal_xml: eTree.Element,
        total_value_key: str = ".//ICMSTot/vProd",
        total_discount_key: str = ".//ICMSTot/vDesc",
        amount_change_key: str = ".//vTroco",
        total_other_values_key: str = ".//ICMSTot/vOutro",
        total_delivery_key: str = ".//ICMSTot/vFrete",
    ) -> None:

        self.total_value = float(fiscal_xml.find(total_value_key).text)
        self.total_discount = float(fiscal_xml.find(total_discount_key).text or 0)
        self.amount_change = float(optional(element=fiscal_xml.find(amount_change_key)) or 0)
        self.total_paid = round_half_away_from_zero(
            number=self.total_value - self.total_discount,
            precision=2,
        )
        self.total_other_values = float(optional(element=fiscal_xml.find(total_other_values_key)) or 0)
        self.total_delivery = float(optional(element=fiscal_xml.find(total_delivery_key)) or 0)
        self.total_addition = round_half_away_from_zero(
            number=self.total_other_values + self.total_delivery,
            precision=2,
        )
