from flask import request
from app import get_app_url

_MAX_RESULTS_PER_PAGE = 100

def add_pagination(query, url):
  """ Adds optional pagination to the given query by looking for the Docker V2 pagination request
      args. """
  limit = request.args.get('n', None)
  page = request.args.get('page', 1)

  if limit is None:
    return None, query

  limit = max(limit, _MAX_RESULTS_PER_PAGE)
  url = get_app_url() + url
  query = query.paginate(page, limit)
  link = url + '?n=%s&last=%s; rel="next"' % (limit, page + 1)
  return link, query