import json

from pos_model import (
    SaleItem,
    TaxItem,
)
from typing import List

from common import (
    CalculateTaxesItemCommon,
    FiscalParameterController,
)


def build_item_taxes(
    sale_item,                      # type: SaleItem
    fiscal_parameter_controller,    # type: FiscalParameterController
    calculate_taxes_common,         # type: CalculateTaxesItemCommon
):
    # type: (...) -> List[TaxItem]

    taxes_calc = fiscal_parameter_controller.get_tip_params(part_code=sale_item.part_code)
    cst_icms = fiscal_parameter_controller.get_tip_params(
        part_code=sale_item.part_code,
        taxes_name=['CST_ICMS'],
    )
    cst_icms = None if len(cst_icms) == 0 else {sale_item.part_code: cst_icms[0]['rate']}
    base_reduction = fiscal_parameter_controller.get_tip_params(
        part_code=sale_item.part_code,
        taxes_name=['BASE_REDUCTION'],
    )
    base_reduction = None if len(base_reduction) == 0 else {sale_item.part_code: base_reduction[0]['rate']}
    taxes = json.dumps(taxes_calc).encode("utf-8")
    item_taxes = calculate_taxes_common.get_taxes_item(
        sale_line=sale_item,
        taxes_calc=taxes,
        base_reduction=base_reduction,
        cst=cst_icms,
    )

    return item_taxes
