import asyncio


class _UserAccountSearchGenerator(object):
    def __init__(self, client, **kwargs):
        self.client = client
        self.kwargs = kwargs
        self.total_pages = 1
        self.current_page = 1
        self.acc_ids = set()
        self.acc_ids_buffer = asyncio.Queue()

    @asyncio.coroutine
    def __aiter__(self):
        return self

    @asyncio.coroutine
    def __anext__(self):
        if self.current_page > self.total_pages and self.acc_ids_buffer.empty():
            raise StopAsyncIteration  # noqa
        if self.acc_ids_buffer.empty():
            data = yield from self.client.user_account_search(page=self.current_page, **self.kwargs)
            self.current_page += 1
            self.total_pages = data['total_pages']
            print(data)
            for record in data['data']:
                acc_id = record['acc_id']
                if acc_id not in self.acc_ids:
                    self.acc_ids.add(acc_id)
                    self.acc_ids_buffer.put_nowait(record)
        return self.acc_ids_buffer.get_nowait()


class AsyncShims(object):
    def _user_account_search_iter(self, *, properties, order=None, filter=None, limit=100, **kwargs):
        return _UserAccountSearchGenerator(
            self, properties=properties, order=order,
            filter=filter, limit=limit, **kwargs)
