import json

from xml.etree import cElementTree as eTree

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: str
        base_reduction,     # type: Dict
        cst,                # 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,
        )).encode('utf-8')

        msg = self.mb_context.MB_EasyEvtSend("TAX_CALC_ITEM", "", data, synchronous=True)
        if msg.token == TK_SYS_ACK:
            return self._tax_decode(data=data)

        return []

    @staticmethod
    def _tax_decode(
        data,   # type: str
    ):
        # type: (...) -> List[TaxItem]

        tax_items_xml = eTree.XML(data)
        tax_items = []

        for tax_item in tax_items_xml.findall("TaxItem"):
            tax = TaxItem()
            tax.tax_name = tax_item.get("taxName")
            tax.tax_rate = tax_item.get("taxRate")
            tax.tax_index = tax_item.get("taxIndex")
            tax.tax_rule_id = tax_item.get("taxRuleId")
            tax.base_amount_ad = tax_item.get("baseAmountAD")
            tax.base_amount_bd = tax_item.get("baseAmountBD")
            tax.base_reduced_amount = tax_item.get("baseReducedAmount")
            tax.tax_amount_ad = tax_item.get("taxAmountAD")
            tax.tax_amount_bd = tax_item.get("taxAmountBD")
            tax.tax_included = tax_item.get("taxIncluded")

            tax_items.append(tax)

        return tax_items
