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


class CertificateManager(NannyRpcClientBase):
    _RPC_URL = "https://awacs.yandex-team.ru/api/"
    _OAUTH_SLUG = 'awacs'
    _API_STUB = api_stub.CertificateServiceStub
    _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 order_https_certificate(self, namespace_id, author='', comment=''):
        order_dict = {
            'meta':
                {
                    'id': namespace_id,
                    'namespace_id': namespace_id,
                    'author': author,
                    'comment': comment,
                    'auth': {
                        'type': "STAFF",
                        'staff': {
                            'owners': {
                                "group_ids": ["29985", ],
                            }
                        }
                    },
                },
            'order':
                {
                    'ca_name': 'InternalCA',
                    'common_name': namespace_id,
                    'public_key_algorithm_id': 'ESS',
                    'abc_service_id': 664,
                }
        }
        order_sertificate_request = api_pb2.OrderCertificateRequest()
        json_format.ParseDict(order_dict, order_sertificate_request)
        return self._CLIENT.order_certificate(order_sertificate_request)

    def get_certificate(self, namespace_id, certificate_id):
        get_sertificate_request = api_pb2.GetCertificateRequest()
        get_sertificate_request.namespace_id = namespace_id
        get_sertificate_request.id = certificate_id
        return self._CLIENT.get_certificate(get_sertificate_request)
