import logging

from app import app
from data.database import UseThenDisconnect
from data.model.repository import find_repository_with_garbage, garbage_collect_repo
from workers.worker import Worker

logger = logging.getLogger(__name__)

class GarbageCollectionWorker(Worker):
  def __init__(self):
    super(GarbageCollectionWorker, self).__init__()
    self.add_operation(self._garbage_collection_repos, 10)

  def _garbage_collection_repos(self):
    """ Performs garbage collection on repositories. """
    with UseThenDisconnect(app.config):
      repository = find_repository_with_garbage(app.config.get('EXP_ASYNC_GARBAGE_COLLECTION', []))
      if repository is None:
        logger.debug('No repository with garbage found')
        return

      logger.debug('Starting GC of repository #%s (%s)', repository.id, repository.name)
      garbage_collect_repo(repository)
      logger.debug('Finished GC of repository #%s (%s)', repository.id, repository.name)
      return

if __name__ == "__main__":
  worker = GarbageCollectionWorker()
  worker.start()
