from redis.client import Redis

class EntityCollection:
    def __init__(self, parent, entity_key):
        self.__parent = parent
        self.__redis_client : Redis = self.__parent.get_context().get_redis_client()
        self.__entity_key_list = entity_key.format(container_name='_list', **self.__parent.__dict__)
        self.__entity_key_set = entity_key.format(container_name='_set', **self.__parent.__dict__)

    def add(self, entity_uuid):
        if self.__redis_client.sismember(self.__entity_key_set, entity_uuid) == 1: return
        self.__redis_client.sadd(self.__entity_key_set, entity_uuid)
        self.__redis_client.rpush(self.__entity_key_list, entity_uuid)

    def get(self):
        return list(map(lambda m: m.decode('UTF-8'), self.__redis_client.lrange(self.__entity_key_list, 0, -1)))

    def contains(self, entity_uuid):
        return self.__redis_client.sismember(self.__entity_key_set, entity_uuid) == 1

    def delete(self, entity_uuid):
        if self.__redis_client.sismember(self.__entity_key_set, entity_uuid) == 0: return
        self.__redis_client.srem(self.__entity_key_set, entity_uuid)
        self.__redis_client.lrem(self.__entity_key_list, 1, entity_uuid)
