import sysactions

from pos_model import Order
from xml.etree import cElementTree as eTree
from helper import remove_accents


class InfAdicBuilderCommon(object):
    def __init__(self, order, customer_text_field, tax_builder):
        self.customer_text_field = customer_text_field
        self.tax_builder = tax_builder
        self.order = order

    def build_common(self):
        # type: () -> unicode

        return u"<infAdic><infCpl>{0}</infCpl></infAdic>".format(self._get_inf_cpl())

    def _get_inf_cpl(self):
        # type: () -> unicode

        xml = self._get_order_identifier(self.order.order_picture_xml)
        xml += self._get_tax_data(self.order.order_picture_xml)
        xml += remove_accents(self.customer_text_field.replace('\n', ''))

        return xml.strip()

    def _get_tax_data(self, order):
        # type: (Order) -> unicode

        total_taxes = self.tax_builder.ibpt_tax_calculator(order)
        total_tax_amount = float(total_taxes['nacionalfederal']['value']) + float(total_taxes['estadual']['value'])
        xml = "%-44s R$%7.2f - " % ("Valor aproximado dos tributos deste cupom", total_tax_amount)
        xml += "Fed. R$%7.2f (%.2f%%) Est. R$%7.2f (%.2f%%)" % (total_taxes['nacionalfederal']['value'],
                                                                total_taxes['nacionalfederal']['percent'],
                                                                total_taxes['estadual']['value'],
                                                                total_taxes['estadual']['percent'])
        xml += " (Conforme Lei Fed. 12.741/2012)"

        return remove_accents(xml)

    def _get_order_identifier(
        self,   # type: InfAdicBuilderCommon
        order,  # type: eTree.Element
    ):
        # type: (...) -> unicode

        order_id = order.get("orderId")
        user_id = order.get("sessionId").split("user=")[1].split(",")[0]
        user_info = sysactions.get_user_information(user_number=user_id)

        operator_name = user_id
        if user_info:
            user = eTree.XML(user_info).find(".//user")
            operator_name = user.get("LongName")[:15] if user is not None else user_id

        table_property = order.find("CustomOrderProperties/OrderProperty[@key='TABLE_ID']")
        table_id = table_property.get("value") if table_property is not None else None
        if table_id:
            order_label = "Pedido/Mesa: {}/{}".format(order_id[-4:], table_id)
        else:
            order_label = "Pedido: {}".format(order_id[-4:])

        xml = "Operador: {}  {} ".format(operator_name, order_label)
        xml += self._get_delivery_partner_and_short_reference(order)

        return remove_accents(xml)

    @staticmethod
    def _get_delivery_partner_and_short_reference(
        order,  # type: eTree.Element
    ):
        # type: (...) -> str

        delivery_partner = order.find("CustomOrderProperties/OrderProperty[@key='PARTNER']")
        if delivery_partner is not None:
            short_reference = order.find("CustomOrderProperties/OrderProperty[@key='SHORT_REFERENCE']")
            if short_reference is not None:
                return "{}: {} ".format(delivery_partner.get("value").upper(), short_reference.get("value").upper())

        return " "
