import json
import os
import urllib.request as request


def make_attaches(event):
    """Slackのリクエストボディ attachmentsを作成する"""
    attachments = []
    for evt in event.get('Records'):
        sns_event = evt.get('Sns')
        event_subscription_arn = evt.get('EventSubscriptionArn')
        subject = sns_event.get('Subject')
        if subject is None:
            subject = 'AWS Notification Message'
        sns_timestamp = sns_event.get('Timestamp')
        message = sns_event.get('Message')
        message_id = sns_event.get('MessageId')
        
        attachments.append({
            "fallback": f"Notification from mbj-newdwh2021 AWS: {event_subscription_arn}",
            "pretext": f"Notification from mbj-newdwh2021 AWS: {event_subscription_arn}",
            "color":"#0000D0",
            "fields":[
                {
                    "title": f"{subject}",
                    "value": f"{sns_timestamp}: {message} (MessageId: {message_id})",
                    "short": False
                }
            ]
        })

    return attachments


def lambda_handler(event, context):
    attachments = make_attaches(event)
    request_url = os.environ.get('SLACK_WEBHOOK_URL')
    payload = {
        'attachments': attachments
    }
    headers = {
        'Content-Type': 'application/json',
    }
    print(payload)

    req = request.Request(request_url, json.dumps(payload, ensure_ascii=False).encode(), headers, method='POST')
    
    with request.urlopen(req) as res:
        body = res.read()

    print(body)
