# coding: utf-8

from __future__ import unicode_literals

import yenv
from ids.connector import HttpConnector
from ids.connector import plugins_lib

from cab.utils import auth
from cab.utils import helpers


class ABCApiConnector(HttpConnector):

    default_connector_timeout = 0.5

    url_patterns = dict(
        members='/api/v3/services/members/',
        services='/api/v3/services/',
    )
    available_auth_types = (
        'oauth',
        'session_id',
    )

    plugins = (
        auth.MultiAuthPlugin,
        plugins_lib.JsonResponse,
    )

    @property
    def config(self):
        return yenv.choose_key_by_type({
            'testing': {
                'protocol': 'https',
                'host': 'abc-back.test.yandex-team.ru',
            },
            'production': {
                'protocol': 'https',
                'host': 'abc-back.yandex-team.ru',
            },
        }, fallback=True)


class ABCPaginator(object):

    def __init__(self, connector, resource, params):
        self.connector = connector
        self.resource = resource
        self.params = params

    def __iter__(self):
        page = self.connector.get(
            resource=self.resource,
            params=self.params,
        )
        page_num = 1
        has_something = True
        while has_something:
            for it in page['results']:
                yield it
            has_something = bool(page['next'])
            if has_something:
                page_num += 1
                page = self.connector.get(
                    resource=self.resource,
                    params=dict(page=page_num, **self.params),
                )


@helpers.timeit
def get_subordinate_vteams(auth, login):
    connector = ABCApiConnector(
        auth=auth,
        user_agent='cab',
    )
    roles = ABCPaginator(
        connector=connector,
        resource='members',
        params=dict(person__login=login),
    )
    services_ids = ','.join(str(it['service']['id']) for it in roles)
    services = ABCPaginator(
        connector=connector,
        resource='services',
        params=dict(id__in=services_ids),
    )

    def is_vteam(service):
        return any(
            tag['name']['en'] == 'v-team'
            for tag in service['tags']
        )

    return [
        dict(
            id=srv['id'],
            name=srv['name'],
            slug=srv['slug'],
        )
        for srv in services
        if srv['owner']['login'] == login and is_vteam(srv)
    ]
