from datetime import datetime

from xml.etree import cElementTree as eTree

from model.log import LogEntry
from processor.event import EventProcessor


def _get_log_entry_from_pos_event(
    data,           # type: str
    event_type,     # type: str
):
    # type: (...) -> LogEntry

    event = eTree.fromstring(data)
    event_data = event[0] if "Event" in event.tag else event
    utc_now = datetime.utcnow()
    created_at = utc_now.strftime("%Y-%m-%d %H:%M:%S")

    return LogEntry(
        pos_id=event_data.get("posId", event_data.get("posid")) or -1,
        business_period=event_data.get("businessPeriod", utc_now.strftime("%Y%m%d")),
        event_type=event_type,
        created_at_gmt=created_at,
        session_id=event_data.get("sessionId"),
        event_data=data,
    )


class GenericEventProcessor(EventProcessor):

    def parse_data(
        self,           # type: GenericEventProcessor
        data,           # type: str
        event_type,     # type: str
    ):
        # type: (...) -> LogEntry

        return _get_log_entry_from_pos_event(
            data=data,
            event_type=event_type,
        )
