from infra.awacs.proto import api_pb2, api_stub
from saas.library.python.nanny_proto.rpc_client_base import NannyRpcClientBase
from saas.library.python.deploy_manager_api.client import DeployManagerApiClient
from google.protobuf import json_format
from saas.library.python.awacs.configs import ConfigManager
from saas.library.python.awacs import helpers
import nanny_rpc_client


class BackendManager(NannyRpcClientBase):
    _RPC_URL = "https://awacs.yandex-team.ru/api/"
    _OAUTH_SLUG = 'awacs'
    _API_STUB = api_stub.BackendServiceStub
    _API_DM = None

    @classmethod
    def _init_dm_client(cls):
        if cls._API_DM is None:
            cls._API_DM = DeployManagerApiClient()

    def __init__(self):
        super(NannyRpcClientBase, self).__init__()
        self._init_client()
        self._init_dm_client()

    def remove_backend(self, ctype, backend_id):
        req_pb = api_pb2.RemoveBackendRequest()
        backend = self.get_backend(ctype, backend_id)
        req_pb.id, req_pb.namespace_id, req_pb.version = backend.meta.id, backend.meta.namespace_id, backend.meta.version
        return self._CLIENT.remove_backend(req_pb)

    def create_backend(self, ctype, *args, **kwargs):
        kwargs['namespace_id'] = helpers.namespace_id_from_ctype(ctype)
        req_pb = api_pb2.CreateBackendRequest()
        config_manager = ConfigManager()
        request_data = config_manager.render_backend_config(*args, **kwargs)
        json_format.ParseDict(request_data, req_pb)
        self._CLIENT.create_backend(req_pb)

    def list_backends(self, ctype):
        req_pb = api_pb2.ListBackendsRequest()
        req_pb.namespace_id = helpers.namespace_id_from_ctype(ctype)
        return self._CLIENT.list_backends(req_pb)

    def backends_by_endp(self, endpointset):
        req_pb = api_pb2.ListBackendsRequest()
        json_format.ParseDict({"query": {"ypEndpointSetFullIdIn": endpointset}}, req_pb)
        return self._CLIENT.list_backends(req_pb).backends

    def get_backend(self, ctype, backend_id):
        req_pb = api_pb2.GetBackendRequest()
        req_pb.id = backend_id
        req_pb.namespace_id = helpers.namespace_id_from_ctype(ctype)
        try:
            return self._CLIENT.get_backend(req_pb).backend
        except nanny_rpc_client.exceptions.NotFoundError:
            return None

    def is_backend_exist(self, ctype, backend_id):
        try:
            self.get_backend(ctype, backend_id)
            return True
        except nanny_rpc_client.exceptions.NotFoundError:
            return False
