from xml.etree import ElementTree as eTree
from common import TipBuilderCommon
from helper import remove_accents
from typing import Dict


class PrinterCommon(object):
    def __init__(self, tip_config, tip_config_range, tip_builder_common):
        # type: (Dict, Dict, TipBuilderCommon) -> None

        self.tip_config = tip_config
        self.tip_config_range = tip_config_range
        self.tip_builder_common = tip_builder_common

    def get_tip_order(self, order):
        # type: (eTree) -> str

        if len(self.tip_config_range) == 0 and len(self.tip_config) == 0:
            return ""

        order_tip = float(order.get("tip"))
        if len(self.tip_config_range) == 0 and len(self.tip_config) > 0:
            return self._get_tip_line(self.tip_config['TipCode'], self.tip_config['TipName'], order_tip)

        report = ""
        order_value = float(order.get("totalGross"))
        percentage_discount_order = abs((order_tip / order_value) * 100)
        percentages = self.tip_builder_common.get_percentage_by_tip(percentage_discount_order)

        for code, percentage in percentages.items():
            line = filter(lambda elem: elem.get("TipCode") == code, self.tip_config_range)[0]
            value = self.tip_builder_common.value_tip_by_percentage(percentage, order_value)
            report += self._get_tip_line(line.get("TipCode"), line.get("TipName"), value)

        return report

    @staticmethod
    def value_tip_by_percentage(percent, order_value):
        # type: (float, float) -> float

        return (percent * order_value) / 100.0

    @staticmethod
    def _get_tip_line(code, description, value):
        # type: (str, str, float) -> str

        order_tip_format = "%-7.7s %-18.18s%6.3f%2.2s%9.02f"
        tip_line = remove_accents(order_tip_format % (code, description, float(1), "un", value))
        return "%-46.46s %9.02f\n" % (tip_line, value)
