# coding: utf-8

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

from clusterpb.federated_stub import FederatedClusterServiceStub
from clusterpb import federated_pb2, hq_pb2, hq_stub

from nanny_rpc_client import RetryingRpcClient

from saas.library.python.nanny_proto.rpc_client_base import NannyRpcClientBase


class Hq(NannyRpcClientBase):
    _identity = []
    _RPC_URL = 'http://federated.yandex-team.ru/rpc/federated/'
    _API_STUB = FederatedClusterServiceStub

    def __init__(self):
        super(Hq, self).__init__()

    @classmethod
    def list_clusters(cls):
        cls._init_client()
        req = federated_pb2.FindClustersRequest()
        res = cls._CLIENT.find_clusters(req)  # type: federated_pb2.FindClustersResponse
        return [c for c in res.value]

    @classmethod
    def get_instances(cls, service_name, geo=None):
        find_req = hq_pb2.FindInstancesRequest()
        find_req.filter.service_id = service_name

        instances = []
        clusters = cls.list_clusters()
        if geo:
            geo_clusters = [c for c in clusters if geo in c.meta.name]
            if len(geo_clusters) > 1:
                raise RuntimeError('More than one HQ cluster in geo location "{}": {}'.format(geo, geo_clusters))
            elif len(geo_clusters) < 1:
                raise RuntimeError('No Hq clusters detected for geo location "{}"'.format(geo))
            clusters = geo_clusters

        for cluster in clusters:
            client = RetryingRpcClient(cluster.spec.endpoint.url + 'rpc/instances/', request_timeout=10)
            hq_client = hq_stub.InstanceServiceStub(client)
            resp = hq_client.find_instances(find_req)
            instances.extend(resp.instance)

        return instances

    @classmethod
    def get_instance_hostnames(cls, service_name, geo=None):
        instances = cls.get_instances(service_name, geo)
        return [i.spec.hostname for i in instances]
