from django.utils.functional import LazyObject
from itertools import starmap

__all__ = ['QueryResults', 'EmptyQueryResults']

def add_obj(result, instance):
    result.object = instance
    return result

class EmptyQueryResults(object):
    def __len__(self):
        return 0

    def __getitem__(self, index):
        return []

class QueryResults(LazyObject):
    def __init__(self, search_results, refine_query):
        self._wrapped = search_results
        self.refine_query = refine_query

    def _setup(self):
        # do nothing
        pass

    def __len__(self):
        return self._wrapped.count()

    def __getitem__(self, index):
        sliced_search_results = self._wrapped[index]
        if isinstance(index, slice):
            sliced_search_results = starmap(
                add_obj,
                zip(sliced_search_results, self.refine_query(sliced_search_results.to_queryset()))
            )
        return sliced_search_results
