from old_helper import round_half_away_from_zero
from pos_model import Order
from typing import (
    Any,
    Dict,
)

from _ContextKeys import ContextKeys
from _SatXmlPartBuilder import SatXmlPartBuilder
from satbuilder import (
    DetBuilder,
    DetFeeBuilder,
    DetTipBuilder,
)


class DetListBuilder(SatXmlPartBuilder):

    def __init__(
        self,               # type: DetListBuilder
        det_builder,        # type: DetBuilder
        det_tip_builder,    # type: DetTipBuilder
        det_fee_builder,    # type: DetFeeBuilder
    ):
        # type: (...) -> None

        self.det_builder = det_builder
        self.det_tip_builder = det_tip_builder
        self.det_fee_builder = det_fee_builder

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

        xml = ""

        context[ContextKeys.total_vbc] = 0
        context[ContextKeys.total_prod] = 0
        context[ContextKeys.total_icms] = 0
        context[ContextKeys.total_pis] = 0
        context[ContextKeys.total_cofins] = 0
        context[ContextKeys.item_no] = 1

        fee_items = self.det_fee_builder.fee_service.get_fee_sale_items(order=order)

        for sale_item in order.sale_items:
            if fee_items:
                sale_item.item_price = round_half_away_from_zero(
                    number=sale_item.item_price - sale_item.fee_included,
                    precision=3,
                )
            context[ContextKeys.current_sale_item] = sale_item
            xml += self.det_builder.build_xml(
                order=order,
                context=context,
            )
            context[ContextKeys.item_no] += 1

        xml += self.det_fee_builder.build_xml(
            order=order,
            context=context,
        )
        xml += self.det_tip_builder.build_xml(
            order=order,
            context=context,
        )

        return xml
