import base64
from typing import Optional
from xml.etree import cElementTree as eTree

from helper import remove_xml_namespace
from messagebus import (
    MessageBus,
)
from order_api import OrderService


class OrderAPIRepository(object):

    def __init__(
        self,
        message_bus: MessageBus,
    ) -> None:

        self._message_bus = message_bus

    def get_order_service(
        self,
        pos_id: int,
    ) -> OrderService:

        return OrderService(
            message_bus=self._message_bus,
            pos_id=pos_id,
        )

    def get_order_picture(
        self,
        pos_id: int,
        order_id: int,
    ) -> Optional[eTree.Element]:

        order_service = self.get_order_service(pos_id=pos_id)
        return order_service.get_order_picture(order_id=order_id)

    def get_fiscal_xml(
        self,
        pos_id: int,
        order_id: int,
        order_xml: Optional[eTree.Element] = None,
    ) -> eTree.Element:

        if not order_xml:
            order_service = self.get_order_service(pos_id=pos_id)
            order_xml = order_service.get_order_picture(order_id=order_id)

        fiscal_xml_base_64 = order_xml.find(".//OrderProperty[@key='FISCAL_XML']").get("value")

        return remove_xml_namespace(xml=base64.b64decode(s=fiscal_xml_base_64).decode())
