import json

from msgbus import MBEasyContext, TK_SYS_ACK
from pos_model import TaxItem, SaleItem
from typing import Dict, List


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

        self.mb_context = mb_context

    def get_taxes_item(
        self,               # type: CalculateTaxesItemCommon
        sale_line,          # type: SaleItem
        taxes_calc,         # type: List
        base_reduction,     # type: Dict
        cst_icms,           # type: Dict
    ):
        # type: (...) -> List[TaxItem]

        data = json.dumps(dict(
            partCode=sale_line.part_code,
            productName=sale_line.product_name,
            quantity=sale_line.quantity,
            unitPrice=sale_line.unit_price,
            itemPrice=sale_line.item_price,
            taxesCalc=taxes_calc,
            baseReduction=base_reduction,
            cst=cst_icms,
        )).encode('utf-8')

        msg = self.mb_context.MB_EasyEvtSend("TAX_CALC_ITEM", "", data, synchronous=True)
        if msg.token == TK_SYS_ACK:
            return json.loads(msg.data, object_hook=self.tax_decode)

        return []

    @staticmethod
    def tax_decode(data):
        # type: (Dict) -> TaxItem

        tax = TaxItem()
        tax.tax_code = data.get("code")
        tax.tax_name = data.get("tax_name")
        tax.tax_rate = data.get("tax_rate")
        tax.tax_index = data.get("tax_index")
        tax.tax_rule_id = data.get("tax_rule_id")
        tax.base_amount_ad = data.get("base_amount_ad")
        tax.base_amount_bd = data.get("base_amount_bd")
        tax.base_reduced_amount = data.get("base_reduced_amount")
        tax.tax_amount_ad = data.get("tax_amount_ad")
        tax.tax_amount_bd = data.get("tax_amount_bd")
        tax.tax_included = data.get("tax_included")

        return tax
