from old_helper import get_class_by_name
from pos_model import SaleItem, TaxItem
from taxcalculator.repository import NTaxCalcRepository
from typing import List, Optional
from msgbus import MBEasyContext


class GeneralTaxCalculator(object):
    def __init__(self, mb_context):
        # type: (MBEasyContext) -> None

        self.mb_context = mb_context
        self.n_tax_calc_repository = NTaxCalcRepository(mb_context)
        self.tip_taxes = None
        self.tax_calculators = []

    def calculate_all_taxes(self, sale_item, tax_calculators=None):
        # type: (SaleItem, Optional[List]) -> List[TaxItem]

        calculators = self._get_tax_calculators() if tax_calculators is None else tax_calculators
        previous_taxes = []
        for tax_calculator in calculators:
            tax_item = tax_calculator.calculate_tax(sale_item, previous_taxes)
            if tax_item is not None:
                previous_taxes.append((sale_item, tax_item))

        calculates_taxes = []
        for tax_tuple in previous_taxes:
            calculates_taxes.append(tax_tuple[1])

        return calculates_taxes

    def _get_tax_calculators(self):
        # type: () -> []

        if len(self.tax_calculators) > 0:
            return self.tax_calculators

        taxes = self.n_tax_calc_repository.load_all_taxes()

        for tax in taxes:
            tax_products = self.n_tax_calc_repository.load_all_products_from_tax(tax.code)

            klz = get_class_by_name(tax.tax_processor)
            params = tax.params
            tax_calculator = klz(self.mb_context, tax.code, tax.name, tax.fiscal_index, tax.rate, tax_products, params)

            self.tax_calculators.append(tax_calculator)

        return self.tax_calculators
