# coding: utf-8

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

from infra.yp_service_discovery.api import api_pb2
from infra.yp_service_discovery.python.resolver.resolver import Resolver as ProtoResolver

from saas.library.python.yp_service_discovery.errors import ResolverError
from saas.library.python.yp_service_discovery.endpoint import Endpoint


class Resolver(ProtoResolver):
    def resolve_endpoint_set(self, cluster, endpoint_set_id, label_selectors=None, ruid=None):
        request = api_pb2.TReqResolveEndpoints(
            cluster_name=cluster,
            endpoint_set_id=endpoint_set_id,
        )
        if label_selectors:
            request.label_selectors.extend(label_selectors)
        if ruid:
            request.ruid = ruid

        response = self.resolve_endpoints(request)
        if ruid and response.ruid != ruid:
            raise ResolverError('ruid mismatch')
        elif response.resolve_status != api_pb2.EResolveStatus.OK:
            raise ResolverError('Resolve status {}'.format(response.resolve_status))
        else:
            return [Endpoint(endpoint, label_selectors) for endpoint in response.endpoint_set.endpoints]
