from redis import Redis


class EventAttr:
    event_attr = dict()

    def __init__(self, rdb: Redis):
        self.rdb = rdb

    def get_event_attr(self, key):
        attr = self.event_attr.get(key)
        if not attr:
            self.event_attr[key] = self.rdb.smembers(key) or set()
        return set(self.event_attr[key])

    def set_event_attr(self, key, *data):
        self.rdb.sadd(key, *data)
        self.event_attr[key] = data

    def check_attr(self, db, data):
        event_name = data.get('#event_name')
        if not event_name:
            return

        key = f'{db}_event_{event_name}'

        attr = self.get_event_attr(key)
        data_attr = set(data)
        extra_attr = data_attr - attr

        if extra_attr:
            self.set_event_attr(key, *extra_attr)
