# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from six.moves import queue

from infra.nanny.nanny_services_rest.nanny_services_rest.client import ServiceRepoClient

from saas.library.python.token_store import PersistentTokenStore

from .service import NannyServiceBase


class NannyServiceIterator(object):
    def __init__(self, category='/', filter_=None):
        """
        :param category: Nanny service category (path). For example /saas/cloud/prod/
        :param filter_: Lambda (NannyService) -> bool
        """
        self._nanny = ServiceRepoClient('https://nanny.yandex-team.ru', token=PersistentTokenStore.get_token_from_store_or_env('nanny'))
        self._category = category
        self._filter = filter_
        self._page_size = 100
        self._skip = 0
        self._buffer = queue.Queue(maxsize=self._page_size * 2)

    def __iter__(self):
        return self

    def __next__(self):
        while self._buffer.empty():
            params = dict(limit=self._page_size, skip=self._skip, category=self._category)
            services = [
                NannyServiceBase(name=s['_id'], runtime_attrs=s['runtime_attrs'], info_attrs=s['info_attrs'])
                for s in
                self._nanny._request_with_retries(method='GET', url='/v2/services/', params=params)['result']
            ]
            self._skip += len(services)
            if not services:
                raise StopIteration
            if self._filter:
                services = filter(self._filter, services)
            for service_ in services:
                self._buffer.put_nowait(service_)
        return self._buffer.get_nowait()

    def next(self):
        return self.__next__()
