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)
    taxes = json.dumps(taxes_calc).encode("utf-8")

    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']}

    cst_dict = _get_cst_dict(
        fiscal_parameter_controller=fiscal_parameter_controller,
        part_code=sale_item.part_code,
    )
    item_taxes = calculate_taxes_common.get_taxes_item(
        sale_line=sale_item,
        taxes_calc=taxes,
        base_reduction=base_reduction,
        cst=cst_dict
    )

    return item_taxes


def _get_cst_dict(
    fiscal_parameter_controller,
    part_code,
):
    cst = {}

    cst_pis = fiscal_parameter_controller.get_tax_value_from_loader(part_code, 'CST_PIS')
    cst['CST_PIS'] = cst_pis

    cst_icms = fiscal_parameter_controller.get_tax_value_from_loader(part_code, 'CST_ICMS')
    cst['CST_ICMS'] = cst_icms

    cst_cofins = fiscal_parameter_controller.get_tax_value_from_loader(part_code, 'CST_COFINS')
    cst['CST_COFINS'] = cst_cofins

    return cst
