{% import "%namespace/%name_%version/%sub/services/%service/_shared_macros.j2" as shared_macros %}
{% extends '_base.py.j2' %}

{% block content %}

import logging
import json  # type: ignore

from google.auth.transport.requests import AuthorizedSession  # type: ignore
from google.auth import credentials as ga_credentials  # type: ignore
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.api_core import rest_helpers
from google.api_core import rest_streaming
from google.api_core import gapic_v1
import google.protobuf

from google.protobuf import json_format
{% if service.has_lro %}
from google.api_core import operations_v1
{% endif %}
{% if opts.add_iam_methods or api.has_iam_mixin %}
from google.iam.v1 import iam_policy_pb2  # type: ignore
from google.iam.v1 import policy_pb2  # type: ignore
{% endif %}
{% if api.has_location_mixin %}
from google.cloud.location import locations_pb2 # type: ignore
{% endif %}

from requests import __version__ as requests_version
import dataclasses
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings

{{ shared_macros.operations_mixin_imports(api, service, opts) }}

from .rest_base import _Base{{ service.name }}RestTransport
from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO

try:
    OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
except AttributeError:  # pragma: NO COVER
    OptionalRetry = Union[retries.Retry, object, None]  # type: ignore

try:
    from google.api_core import client_logging  # type: ignore
    CLIENT_LOGGING_SUPPORTED = True  # pragma: NO COVER
except ImportError:  # pragma: NO COVER
    CLIENT_LOGGING_SUPPORTED = False

_LOGGER = logging.getLogger(__name__)

DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
    gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
    grpc_version=None,
    rest_version=f"requests@{requests_version}",
)

if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"):  # pragma: NO COVER
    DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__


{{ shared_macros.create_interceptor_class(api, service, method, is_async=False) }}


@dataclasses.dataclass
class {{service.name}}RestStub:
    _session: AuthorizedSession
    _host: str
    _interceptor: {{ service.name }}RestInterceptor


class {{service.name}}RestTransport(_Base{{ service.name }}RestTransport):
    """REST backend synchronous transport for {{ service.name }}.

    {{ service.meta.doc|rst(width=72, indent=4) }}

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends JSON representations of protocol buffers over HTTP/1.1
    """

    {# TODO(yon-mg): handle mtls stuff if that is relevant for rest transport #}
    def __init__(self, *,
            host: str{% if service.host %} = '{{ service.host }}'{% endif %},
            credentials: Optional[ga_credentials.Credentials] = None,
            credentials_file: Optional[str] = None,
            scopes: Optional[Sequence[str]] = None,
            client_cert_source_for_mtls: Optional[Callable[[
                ], Tuple[bytes, bytes]]] = None,
            quota_project_id: Optional[str] = None,
            client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
            always_use_jwt_access: Optional[bool] = False,
            url_scheme: str = 'https',
            interceptor: Optional[{{ service.name }}RestInterceptor] = None,
            api_audience: Optional[str] = None,
            ) -> None:
        """Instantiate the transport.

       {% if not opts.rest_numeric_enums %}
       NOTE: This REST transport functionality is currently in a beta
       state (preview). We welcome your feedback via a GitHub issue in
       this library's repository. Thank you!
       {% endif %}

        Args:
            host ({% if service.host %}Optional[str]{% else %}str{% endif %}):
                {{ ' ' }}The hostname to connect to {% if service.host %}(default: '{{ service.host }}'){% endif %}.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.

            credentials_file (Optional[str]): Deprecated. A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is ignored if ``channel`` is provided. This argument will be
                removed in the next major version of this library.
            scopes (Optional(Sequence[str])): A list of scopes. This argument is
                ignored if ``channel`` is provided.
            client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
                certificate to configure mutual TLS HTTP channel. It is ignored
                if ``channel`` is provided.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you are developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
            url_scheme: the protocol scheme for the API endpoint.  Normally
                "https", but for testing or local servers,
                "http" can be specified.
            interceptor (Optional[{{ service.name }}RestInterceptor]): Interceptor used
                to manipulate requests, request metadata, and responses.
            api_audience (Optional[str]): The intended audience for the API calls
                to the service that will be set when using certain 3rd party
                authentication flows. Audience is typically a resource identifier.
                If not set, the host value will be used as a default.
        """
        # Run the base constructor
        # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
        # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
        # credentials object
        super().__init__(
            host=host,
            credentials=credentials,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
            url_scheme=url_scheme,
            api_audience=api_audience
        )
        self._session = AuthorizedSession(
            self._credentials, default_host=self.DEFAULT_HOST)
        {% if service.has_lro %}
        self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None
        {% endif %}
        if client_cert_source_for_mtls:
            self._session.configure_mtls_channel(client_cert_source_for_mtls)
        self._interceptor = interceptor or {{ service.name }}RestInterceptor()
        self._prep_wrapped_messages(client_info)

    {% if service.has_lro %}

    @property
    def operations_client(self) -> operations_v1.AbstractOperationsClient:
        """Create the client designed to process long-running operations.

        This property caches on the instance; repeated calls return the same
        client.
        """
        # Only create a new client if we do not already have one.
        if self._operations_client is None:
            http_options: Dict[str, List[Dict[str, str]]] = {
            {% for selector, rules in api.http_options.items() %}
            {% if selector.startswith('google.longrunning.Operations') %}
                '{{ selector }}': [
                    {% for rule in rules %}
                    {
                        'method': '{{ rule.method }}',
                        'uri': '{{ rule.uri }}',
                        {% if rule.body %}
                        'body': '{{ rule.body }}',
                        {% endif %}{# rule.body #}
                    },
                    {% endfor %}{# rules #}
                ],
            {% endif %}{# selector.startswith Operations #}
            {% endfor %}{# http_options #}
            }

            rest_transport = operations_v1.OperationsRestTransport(
                    host=self._host,
                    # use the credentials which are saved
                    credentials=self._credentials,
                    scopes=self._scopes,
                    http_options=http_options,
                    path_prefix="{{ service.client_package_version }}")

            self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport)

        # Return the client from cache.
        return self._operations_client


    {% endif %}{# service.has_lro #}
    {% for method in service.methods.values()|sort(attribute="name") %}
    class {{ method.name|make_private }}(_Base{{ service.name }}RestTransport._Base{{method.name}}, {{service.name}}RestStub):
        def __hash__(self):
            return hash("{{service.name}}RestTransport.{{method.name}}")
        {% if method.http_options and not method.client_streaming %}

        {% set body_spec = method.http_options[0].body %}
        {{ shared_macros.response_method(body_spec, is_async=False, is_streaming_method=method.server_streaming)|indent(8) }}
        {% endif %}{# method.http_options and not method.client_streaming #}

        def __call__(self,
                request: {{method.input.ident}}, *,
                retry: OptionalRetry=gapic_v1.method.DEFAULT,
                timeout: Optional[float]=None,
                {{ shared_macros.client_method_metadata_argument()|indent(8) }}={{ shared_macros.client_method_metadata_default_value() }},
                ){% if not method.void %} -> {% if not method.server_streaming %}{{method.output.ident}}{% else %}rest_streaming.ResponseIterator{% endif %}{% endif %}:
    {% if method.http_options and not method.client_streaming %}
            r"""Call the {{- ' ' -}}
            {{ (method.name|snake_case).replace('_',' ')|wrap(
                    width=70, offset=45, indent=8) }}
            {{- ' ' -}} method over HTTP.

            Args:
                request (~.{{ method.input.ident }}):
                    The request object.{{ ' ' }}
                    {{- method.input.meta.doc|rst(width=72, indent=16, nl=False) }}
                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                {{ shared_macros.client_method_metadata_argument_doc()|indent(8) }}
            {% if not method.void %}

            Returns:
                ~.{{ method.output.ident }}:
                    {{ method.output.meta.doc|rst(width=72, indent=16) }}
            {% endif %}
            """

            {{ shared_macros.rest_call_method_common(body_spec, method.name, service, False, method.input.ident.is_proto_plus_type)|indent(8) }}

            {% if not method.void %}
            # Return the response
            {% if method.lro %}
            resp = operations_pb2.Operation()
            json_format.Parse(response.content, resp, ignore_unknown_fields=True)
            {% elif method.server_streaming %}
            resp = rest_streaming.ResponseIterator(response, {{method.output.ident}})
            {% else %}
            resp = {{method.output.ident}}()
            {% if method.output.ident.is_proto_plus_type %}
            pb_resp = {{method.output.ident}}.pb(resp)
            {% else %}
            pb_resp = resp
            {% endif %}

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            {% endif %}{# method.lro #}
            {#- TODO(https://github.com/googleapis/gapic-generator-python/issues/2274): Add debug log before intercepting a request #} 
            resp = self._interceptor.post_{{ method.name|snake_case }}(resp)
            response_metadata = [(k, str(v)) for k, v in response.headers.items()]
            resp, _ = self._interceptor.post_{{ method.name|snake_case }}_with_metadata(resp, response_metadata)
            if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG):  # pragma: NO COVER
                {# TODO(https://github.com/googleapis/gapic-generator-python/issues/2389): #}
                {# Depending how we want to log (a) receiving a streaming response vs (b) exposing the next streamed item to the user, we could possibly want to log something here #}
                {# (a) should always happen in api-core #}
                {# (b) could happen in api-core, or it could happen here when we iterate to the next streamed item that was previously received. #}
                {% if not method.server_streaming %}
                try:
                    response_payload = {% if method.output.ident.is_proto_plus_type %}{{ method.output.ident }}.to_json(response){% else %}json_format.MessageToJson(resp){% endif %}

                except:
                    {# TODO(https://github.com/googleapis/gapic-generator-python/issues/2283): Remove try/except once unit tests are updated. #}
                    response_payload = None
                {% endif %}{# if not method.server_streaming #}
                http_response = {
                {# Not logging response payload for server streaming here. See comment above. #}
                {% if not method.server_streaming %}
                "payload": response_payload,
                {% endif %}{# if not method.server_streaming #}
                "headers":  dict(response.headers),
                "status": response.status_code,
                }
                _LOGGER.debug(
                    "Received response for {{ service.meta.address.proto_package_versioned }}.{{ service.client_name }}.{{ method.transport_safe_name|snake_case }}",
                    extra = {
                        "serviceName": "{{ service.meta.address.proto }}",
                        "rpcName": "{{ method.name }}",
                        {# TODO(https://github.com/googleapis/gapic-generator-python/issues/2275): logging `metadata` seems repetitive and may need to be cleaned up #}
                        "metadata": http_response["headers"],
                        "httpResponse": http_response,
                    },
                )
            return resp

            {% endif %}{# method.void #}
    {% else %}{# method.http_options and not method.client_streaming #}
            raise NotImplementedError(
                "Method {{ method.name }} is not available over REST transport"
            )
    {% endif %}{# method.http_options and not method.client_streaming #}
    {% endfor %}
    {% for method in service.methods.values()|sort(attribute="name") %}

    @property
    def {{method.transport_safe_name|snake_case}}(self) -> Callable[
            [{{method.input.ident}}],
            {{method.output.ident}}]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._{{method.name}}(self._session, self._host, self._interceptor) # type: ignore

    {% endfor %}

    {% include '%namespace/%name_%version/%sub/services/%service/transports/_rest_mixins.py.j2' %}

    @property
    def kind(self) -> str:
        return "rest"

    def close(self):
        self._session.close()


__all__=(
    '{{ service.name }}RestTransport',
)
{% endblock %}
