from xml.etree import cElementTree as Etree
from datetime import datetime

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


def _get_log_entry_from_order_event(data, _):
    event = Etree.fromstring(data)
    table = _check_mandatory_information(event, data)

    created_at = datetime.strptime(table.get("startTS"), "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%dT%H:%M:%S.000")
    return LogEntry(
        pos_id=event.get("posId", -1),
        session_id=event.get("sessionId", ''),
        business_period=table.get("businessPeriod").replace('-', ''),
        event_type=event.get("subject"),
        created_at_gmt=created_at,
        event_data=Etree.tostring(table)
    )


def _check_mandatory_information(event, data):
    table = event.find(".//Table")
    if table is None:
        raise InvalidTableEventException(data)

    return table


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

        return _get_log_entry_from_order_event(data, event_type)
