from datetime import datetime
from chalicelib.utils.helper import environ

from chalicelib.core.collaboration_slack import Slack


def send(notification, destination):
    if notification is None:
        return
    return Slack.send_text(tenant_id=notification["tenantId"],
                           webhook_id=destination,
                           text=notification["description"] \
                                + f"\n<{environ['SITE_URL']}{notification['buttonUrl']}|{notification['buttonText']}>",
                           title=notification["title"],
                           title_link=notification["buttonUrl"], )


def send_batch(notifications_list):
    if notifications_list is None or len(notifications_list) == 0:
        return
    webhookId_map = {}
    for n in notifications_list:
        if n.get("destination") not in webhookId_map:
            webhookId_map[n.get("destination")] = {"tenantId": n["notification"]["tenantId"], "batch": []}
        webhookId_map[n.get("destination")]["batch"].append({"text": n["notification"]["description"] \
                                                                     + f"\n<{environ['SITE_URL']}{n['notification']['buttonUrl']}|{n['notification']['buttonText']}>",
                                                             "title": n["notification"]["title"],
                                                             "title_link": n["notification"]["buttonUrl"],
                                                             "ts": datetime.now().timestamp()})
    for batch in webhookId_map.keys():
        Slack.send_batch(tenant_id=webhookId_map[batch]["tenantId"], webhook_id=batch,
                         attachments=webhookId_map[batch]["batch"])
