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
        is_mobile=False     # type: bool
    ):
        # type: (...) -> 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, is_mobile)

        report = ""

        total_gross = float(order.get('totalGross'))
        tip_ranges = self.tip_builder_common.get_percentage_by_tip(total_gross, order_tip)
        for key, value in tip_ranges.items():
            report += self._get_tip_line(key, value.get("TipName"), value.get("TipValue"), is_mobile)

        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,           # type: str
        description,    # type: str
        value,          # type: float
        is_mobile       # type: bool
    ):
        # type: (...) -> str

        format_mobile = "%-7.7s %-14.14s%6.3f%-3.2s%9.2f"
        format_desktop = "%-7.7s %-18.18s%6.3f%2.2s%9.02f"
        order_tip_format = format_mobile if is_mobile else format_desktop

        tip_line = remove_accents(order_tip_format % (code, description, float(1), "un", value))

        format_mobile = "%-39.40s %7.02f\n"
        format_desktop = "%-46.46s %9.02f\n"
        order_tip_format = format_mobile if is_mobile else format_desktop

        return order_tip_format % (tip_line, value)
