import logging
import time
import base64


def pull_messages(pubsub_sub, project_name, sub_name):
    """Pulls messages from a given subscription."""
    BATCH_SIZE = 50
    subscription_path = pubsub_sub.subscription_path(project_name, sub_name)
    tweets = []

    try:
        resp = pubsub_sub.pull(request={'subscription': subscription_path, 'max_messages': BATCH_SIZE})
    except Exception as e:
        logging.error(f'PubSub: Error pulling tweets - {e}')
        time.sleep(0.5)
        return

    receivedMessages = resp.received_messages
    if len(receivedMessages) > 0:
        ack_ids = []
        for msg in receivedMessages:
            tweets.append(
                base64.urlsafe_b64decode(msg.message.data)
            )
            ack_ids.append(msg.ack_id)
        pubsub_sub.acknowledge(request={'subscription': subscription_path, 'ack_ids': ack_ids})

        logging.info(f'PubSub: Pulled {len(tweets)} tweets')
    return tweets