from collections import OrderedDict

from django.conf import settings


def paginate_search_results(request, data, count):
    """
    Util method to make the pagination data
    Args:
        request (obj): Requests
        data (dict): Data which needs to be rendered in Response
        count: Count of matching data.
    Returns:
        dict with next, previous link and data count
    """
    try:
        offset = int(request.query_params.get('offset', 0))
    except ValueError:
        offset = 0

    try:
        limit = int(request.query_params.get('limit', settings.SEARCH_RESULTS_LIMIT))
    except ValueError:
        limit = settings.SEARCH_RESULTS_LIMIT

    if limit > settings.SEARCH_RESULTS_LIMIT:
        limit = settings.SEARCH_RESULTS_LIMIT

    def _make_url(request):
        http_path = 'https' if request._request.is_secure() else 'http'
        url = "{}://{}{}".format(http_path, request.META['HTTP_HOST'], request.path)
        return url

    def _get_next_link(offset, limit):
        url = _make_url(request)
        if offset >= count-limit:
            return None
        next_offset = limit + offset
        return url + "?offset={}&limit={}".format(next_offset, limit)

    def _get_previous_link(offset, limit):
        url = _make_url(request)
        if offset == 0:
            return None
        previous_offset = offset - limit
        return url + "?offset={}&limit={}".format(previous_offset, limit)

    return OrderedDict([
        ('metadata', OrderedDict([
            ('count', count),
            ('next', _get_next_link(offset, limit)),
            ('previous', _get_previous_link(offset, limit)),
        ])),
        ('results', data)
    ])
