from datetime import datetime
from typing import (
    Dict,
    Optional,
    Tuple,
)
from xml.etree import cElementTree as eTree
from mwhelper import ModelService
from typing import List
from externals.repository import AlertsRepository
from services.model import ConfiguredAlert
from .table import get_table_picture
from posentitiesformatter import (
    OrderFormatter,
    TableFormatter,
)


def get_configured_alerts_by_type(
    notify_type,        # type: str
    configured_alerts,  # type: list
):
    # type: (...) -> List[ConfiguredAlert]

    alerts = []
    for config in configured_alerts:
        if "notifyOn" in config.alert_json and notify_type == config.alert_json["notifyOn"]:
            alerts.append(config)

    return alerts


def insert_event_into_repository(
    pos_id,                   # type: str
    alerts_repository,        # type: AlertsRepository
    order_picture,            # type: eTree.XML
    alert,                    # type: ConfiguredAlert
    table_picture_dict=None,  # type: Optional[dict]
    order_picture_dict=None,  # type: Optional[dict]
):
    # type: (...) -> Tuple[Dict, Dict]

    timestamp = str(datetime.utcnow())
    notification_json = {
        "alertJSON": alert.alert_json,
        "timestamp": timestamp,
    }
    is_table = ModelService.is_table_service(order_picture)
    if order_picture_dict is None:
        if is_table and table_picture_dict is None:
            table_id = order_picture.find("CustomOrderProperties/OrderProperty[@key='TABLE_ID']").get("value")
            table_picture = eTree.XML(
                get_table_picture(
                    pos_id=pos_id,
                    table_id=table_id,
                )
            )
            table_picture_dict = TableFormatter().get_table_picture_dict(table_picture=table_picture)
            order_picture_dict = OrderFormatter().get_order_picture_dict(order_picture=order_picture)
        else:
            order_picture_dict = OrderFormatter().get_order_picture_dict(order_picture=order_picture)

    notification_json.update({"orderPicture": order_picture_dict})
    if is_table:
        notification_json.update({"tablePicture": table_picture_dict})

    alerts_repository.insert_event(
        alert_id=alert.id,
        notification_json=notification_json,
        timestamp=timestamp,
        sent_status=0,
    )

    return order_picture_dict, table_picture_dict
