from xml.etree import ElementTree as eTree
from common import TipBuilderCommon
from helper import (
    remove_accents,
    encode_cp860,
    custom_encode_cp860,
)
from sysactions import translate_message
from typing import Dict, Optional


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)

    @staticmethod
    def get_coupon_call_id(
        order,                      # type: eTree.Element
        customer_name_limit=None,   # type: Optional[int]
    ):
        # type: (...) -> str

        pager_number = order.find("CustomOrderProperties/OrderProperty[@key='PAGER_NUMBER']")
        if pager_number is not None:
            pager_number = pager_number.get("value")
            if pager_number:
                return pager_number

        customer_name = order.find("CustomOrderProperties/OrderProperty[@key='CUSTOMER_NAME']")
        if customer_name is not None:
            customer_name = customer_name.get("value")
            if customer_name:
                if customer_name_limit:
                    customer_name = customer_name[:customer_name_limit]

                return custom_encode_cp860(text=customer_name)

        return order.get('orderId')[-3:]

    @staticmethod
    def get_coupon_call_text(
        model,      # type: eTree
    ):
        # type: (...) -> str

        panel_call_text = encode_cp860(
            translate_message(
                model=model,
                message_key="CALL_PANEL",
            ),
        )
        will_be_called_text = encode_cp860(
            translate_message(
                model=model,
                message_key="YOU_WILL_BE_CALLED",
            ),
        )

        coupon_call_text = "{} - {}".format(
            panel_call_text,
            will_be_called_text,
        )

        return coupon_call_text
