from xml.etree import cElementTree as Etree

from model.log import LogEntry
from _EventProcessor import EventProcessor


def _get_log_entry_from_pos_event(data, event_type):
    event = Etree.fromstring(data)
    event_data = event[0] if "Event" in event.tag else event

    created_at = event_data.get("created_at_gmt")
    session_id = event_data.get("session_id")
    business_period = session_id.split("period=")[1]

    return LogEntry(
        pos_id=event_data.get("pos_id") or -1,
        order_id=event_data.get("order_id"),
        business_period=business_period,
        event_type=event_type,
        created_at_gmt=created_at,
        session_id=session_id,
        event_data=Etree.tostring(event_data)
    )


class ProductionEventProcessor(EventProcessor):
    def parse_data(self, data, event_type):
        return _get_log_entry_from_pos_event(data, event_type)
