import json

from logging import Logger
from xml.etree import cElementTree as eTree
from util.xml2dict import convert_xml_to_dict
from mbcontextmessagehandler import MbContextMessageBus
from messagebus import Event
from sysactions import (
    get_model,
    get_posot,
)
from services.model import BOHOrderPictureRequest


class BOHOrderPictureInteractor(object):
    def __init__(
        self,
        message_bus,  # type: MbContextMessageBus
        logger,       # type: Logger
    ):
        # type: (...) -> None

        self.message_bus = message_bus
        self.logger = logger
        self.event_action = "BohOrderPictureResponse"

    def process_request(
        self,
        request,  # type: BOHOrderPictureRequest
    ):
        # type: (...) -> None

        if request.pos_id is None or request.order_id is None:
            return

        pos_id = request.pos_id
        order_id = request.order_id
        model = get_model(posid=pos_id)
        pos_ot = get_posot(model=model)
        order_picture = eTree.XML(pos_ot.orderPicture(orderid=order_id)).find("Order")
        self.send_boh_order_picture_response_event(order_picture=order_picture)

    def send_boh_order_picture_response_event(
        self,
        order_picture,  # type: eTree.Element
    ):
        # type: (...) -> None

        try:
            event_data = {
                "orderPicture": convert_xml_to_dict(xml_object=order_picture),
            }
            event = Event(
                subject=self.event_action,
                event_type="",
                data=json.dumps(obj=event_data),
            )
            self.message_bus.publish_event(event=event)
            success_message = "BohOrderPictureResponse event sent successfully! order_id={0}"
            self.logger.info(msg=success_message.format(order_picture.get("orderId")))
        except Exception as _:  # noqa
            self.logger.exception(msg="Error sending BohOrderPictureResponse event")
