# subscriber.py
import redis
from config import Config
from .internal_service_ops import InternalServiceOps
from flask import current_app

class Subscriber():

    def __init__(self):
        self.config = Config().get_config()
        #set this params using config params
        self.r = redis.Redis(host=self.config["redis"]["host"], port=self.config["redis"]["port"], db=self.config["redis"]["db"])
        self.acls_ops = InternalServiceOps()
        self.p = self.r.pubsub()
        self.p.subscribe("acls-messages", "internal-messages")

    def listen(self):
        for raw_message in self.p.listen():
            if raw_message["type"] == "message" and raw_message["channel"].decode('utf-8') == "acls-messages":
                current_app.logger.info("acls-messages recived")
                message, *ids = raw_message["data"].decode('utf-8').split(":")
                if message == "create-acl" and len(ids)==3:
                    self.acls_ops.create_acl(ids[0], ids[1], ids[2])
                if message == "remove-acl" and len(ids)==3:
                    self.acls_ops.remove_acl(ids[0], ids[1], ids[2])
                if message == "remove-acl" and len(ids)==1:
                    self.acls_ops.remove_invoker_acl(ids[0])
            if raw_message["type"] == "message" and raw_message["channel"].decode('utf-8') == "internal-messages":
                message, *ids = raw_message["data"].decode('utf-8').split(":")
                if message == "invoker-removed" and len(ids)>0:
                    self.acls_ops.remove_invoker_acl(ids[0])
                if message == "provider-removed" or message == "service-removed" and len(ids) > 0:
                    self.acls_ops.remove_provider_acls(ids[0])
            



