from .utils import consumer_id
import re

class Subscription:
    def __init__(self, channel, queue=None):
        self.__channel = channel
        self.__ctag = consumer_id()
        self.__queue = queue if queue else self.__ctag
        self.__channel._Channel__queue_declare(queue=self.__queue)
        self.__channel._Channel__queue_bind(queue=self.__queue, routing_key=self.__queue)
        self.__channel._Channel__basic_consume(queue=self.__queue, consumer_tag=self.__ctag)

    def __make_re(self, topic):
        return re.compile(re.sub('[*]', '.+', re.sub('[.]', '\.', topic)))

    def name(self):
        return self.__queue

    def id(self):
        return self.__ctag

    def subscribe(self, topic, fn):
        self.__channel._Channel__queue_bind(
            queue=self.__queue, routing_key=topic)
        self.__channel._Channel__subscriptions[self.__ctag][self.__make_re(topic)] = fn

    def unsubscribe(self, topic):
        self.__channel._Channel__queue_unbind(queue=self.__queue, routing_key=topic)
        re_topic = self.__make_re(topic)
        if re_topic in self.__channel._Channel__subscriptions[self.__ctag]:
            del self.__channel._Channel__subscriptions[self.__ctag][re_topic]