from xml.etree import cElementTree as Etree

from model.exception import InvalidOrderEventException
from model.log import LogEntry
from _EventProcessor import EventProcessor


def _get_log_entry_from_order_event(data, event_type):
    try:
        order = _check_mandatory_information(data)
    except InvalidOrderEventException:
        return None

    pos_id = order.get("posId", order.get("posid"))
    if pos_id is None:
        pos_id = order.get("instance") or -1

    return LogEntry(
        pos_id=pos_id,
        order_id=order.get("orderId", order.get("orderid")),
        business_period=order.get("businessPeriod", order.get("period")),
        event_type=event_type,
        created_at_gmt=order.get("createdAtGMT"),
        session_id=order.get("sessionId", order.get("sessionid")),
        event_data=Etree.tostring(order)
    )


def _check_mandatory_information(data):
    event = Etree.fromstring(data)
    order = event.find(".//Order")
    if order is None or order.get("orderId") is None:
        raise InvalidOrderEventException(data)

    return order


class OrderEventProcessor(EventProcessor):
    def parse_data(self, data, event_type):
        # type: (str, str) -> LogEntry
        return _get_log_entry_from_order_event(data, event_type)
