from json import loads

from requests import get


class APIListIterator(object):
    ''' Iterator for a list of objects generated by the Django Rest Framework API.
    '''

    def __init__(self, api_endpoint, params=None):
        self.api_endpoint = api_endpoint
        self.params = params
        self.objects = []

    def __iter__(self):
        return self

    def next(self):
        if len(self.objects) == 0:
            # No more objects to import
            if self.api_endpoint is None:
                raise StopIteration

            # Get the json representation of the next object in the list and decode
            response = get(self.api_endpoint, params=self.params)
            if response.status_code != 200:
                raise StopIteration
            response_json = loads(response.text)
            if 'count' in response_json and response_json['count'] == 0:
                raise StopIteration
            for obj_summary in response_json['results']:
                obj_details_response = get(obj_summary['url'])
                if obj_details_response.status_code != 200:
                    raise StopIteration
                obj_details = loads(obj_details_response.text)
                self.objects.append(obj_details)

            # If response contains 'next' then there are more objects
            if 'next' in response_json:
                self.api_endpoint = response_json['next']
            else:
                self.api_endpoint = None

        return self.objects.pop()

    __next__ = next  # Python 3.X compatibility
