#import concurrent
import requests
from .internal_event_ops import InternalEventOperations
from ..models.event_notification import EventNotification
from ..models.access_control_policy_list_ext import AccessControlPolicyListExt
from ..models.capif_event_detail import CAPIFEventDetail
from ..encoder import JSONEncoder
import sys
import json
from flask import current_app

class Notifications():

    def __init__(self):
        self.events_ops = InternalEventOperations()

    def send_notifications(self, event):
        current_app.logger.info("Received event, sending notifications")
        subscriptions = self.events_ops.get_event_subscriptions(event)
        # message, *ids = event.split(":")

        try:
            for sub in subscriptions:
                url = sub["notification_destination"]
                data = EventNotification(sub["subscription_id"], events=event)
                # details = CAPIFEventDetail()
                # if message == "ACCESS_CONTROL_POLICY_UPDATE":
                #     current_app.logger.info("event: ACCESS_CONTROL_POLICY_UPDATE")
                #     acls = self.events_ops.get_acls(ids[0])
                #     details.acc_ctrl_pol_list = AccessControlPolicyListExt(api_id=acls['service_id'], api_invoker_policies=acls['apiInvokerPolicies'])

                # data.event_detail=details
                self.request_post(url, data)
                #current_app.logger.info("notification sended")

        except Exception as e:
            current_app.logger.error("An exception occurred ::" + str(e))
            return False

    def request_post(self, url, data):
        headers = {'content-type': 'application/json'}
        return requests.post(url, json={'text': str(data.to_str())}, headers=headers)

